/**
 * 回收iframe内存
 * 覆盖panel控件的默认的销毁事件，注意如果创建时使用该事件，此处的定义将无效
 */
(function($){
	$.fn.panel.defaults.onBeforeDestroy = function() {
	    var frame = $('iframe', this);  
	    if (frame.length > 0) {  
	        frame[0].contentWindow.document.write('');  
	        frame[0].contentWindow.close();  
	        frame.remove();  
	        if ($.browser.msie) {  
	            CollectGarbage();  
	        }  
	    }  
	};
})(jQuery);

/**
 * combobox - jQuery EasyUI
 * 
 */
(function($){
	
	/**
	 * set values
	 */
	function setValues(target, values, remainText, notChange) {
		var opts = $.data(target, 'combobox').options;
		var panel = $(target).combo('panel');

		/* 防止载入值为null时发生错误 start */
		if (!$.isArray(values)) {
			values = values ? String(values).split(opts.separator) : [];
		}
		/* 防止载入值为null时发生错误 end */
		panel.find('div.combobox-item-selected').removeClass(
				'combobox-item-selected');
		var vv = [], ss = [];
		for ( var i = 0; i < values.length; i++) {
			var v = values[i];
			var s = v;
			opts.finder.getEl(target, v).addClass('combobox-item-selected');
			var row = opts.finder.getRow(target, v);
			if (row) {
				s = row[opts.textField];
			}
			vv.push(v);
			ss.push(s);
		}

		if (!remainText) {
			$(target).combo('setText', ss.join(opts.separator));
		}
		if (!notChange) {
			$(target).combo('setValues', vv);
		}
	}
	
	/**
	 * load data, the old list items will be removed.
	 */
	function loadData(target, data, remainText){
		var state = $.data(target, 'combobox');
		var opts = state.options;
		state.data = opts.loadFilter.call(target, data);
		state.groups = [];
		data = state.data;
		
		var selected = $(target).combobox('getValues');
		var dd = [];
		var group = undefined;
		for(var i=0; i<data.length; i++){
			var row = data[i];
			var v = row[opts.valueField]+'';
			var s = row[opts.textField];
			var g = row[opts.groupField];
			
			if (g){
				if (group != g){
					group = g;
					state.groups.push(g);
					dd.push('<div id="' + (state.groupIdPrefix+'_'+(state.groups.length-1)) + '" class="combobox-group">');
					dd.push(opts.groupFormatter ? opts.groupFormatter.call(target, g) : g);
					dd.push('</div>');
				}
			} else {
				group = undefined;
			}
			
			var cls = 'combobox-item' + (row.disabled ? ' combobox-item-disabled' : '') + (g ? ' combobox-gitem' : '');
			dd.push('<div id="' + (state.itemIdPrefix+'_'+i) + '" class="' + cls + '">');
			dd.push(opts.formatter ? opts.formatter.call(target, row) : s);
			dd.push('</div>');
			
			if (row['selected'] && $.inArray(v, selected) == -1){
				selected.push(v);
			}
		}
		$(target).combo('panel').html(dd.join(''));
		
		if (opts.multiple){
			setValues(target, selected, remainText);
		} else {
			setValues(target, selected.length ? [selected[selected.length-1]] : [], remainText);
		}
		
		opts.onLoadSuccess.call(target, data);
	}

	function nav(target, dir) {
		var opts = $.data(target, 'combobox').options;
		var panel = $(target).combobox('panel');
		/* 面板展开时，阻止上下键冒泡 start */
		if(panel.is(':hidden')) return false;
		/* 面板展开时，阻止上下键冒泡 end */
		var item = panel.children('div.combobox-item-hover');
		if (!item.length) {
			item = panel.children('div.combobox-item-selected');
		}
		item.removeClass('combobox-item-hover');
		var firstSelector = 'div.combobox-item:visible:not(.combobox-item-disabled):first';
		var lastSelector = 'div.combobox-item:visible:not(.combobox-item-disabled):last';
		if (!item.length) {
			item = panel.children(dir == 'next' ? firstSelector : lastSelector);
		} else {
			if (dir == 'next') {
				item = item.nextAll(firstSelector);
				if (!item.length) {
					item = panel.children(firstSelector);
				}
			} else {
				item = item.prevAll(firstSelector);
				if (!item.length) {
					item = panel.children(lastSelector);
				}
			}
		}
		if (item.length) {
			item.addClass('combobox-item-hover');
			var row = opts.finder.getRow(target, item);
			if (row) {
				scrollTo(target, row[opts.valueField]);
				/*multiple不要直接选中，使用enter键选中，直接选中对多选不友好*/
				if (opts.selectOnNavigation && !opts.multiple) {
					$(target).combobox('select', row[opts.valueField]);
				}
			}
		}
		return true;
	}

	/**
	 * request remote data if the url property is setted.
	 */
	function request(target, url, param, remainText){
		var opts = $.data(target, 'combobox').options;
		if (url){
			opts.url = url;
		}
		//增加级联参数支持
		param = $.extend({}, opts.queryParams, param||{});
		/*if(opts["onSetQueryParam"]) {
			param = $.extend(true, {}, param, opts["onSetQueryParam"].call(target, param, opts["rowData"], opts["rowIndex"]));
		}*/
//		param = param || {};
		
		if (opts.onBeforeLoad.call(target, param) == false) return;

		opts.loader.call(target, param, function(data){
			loadData(target, data, remainText);
		}, function(){
			opts.onLoadError.apply(this, arguments);
		});
	}
	
	/**
	 * do the query action
	 */
	function doQuery(target, q){
		var state = $.data(target, 'combobox');
		var opts = state.options;
		
		var qq = opts.multiple ? q.split(opts.separator) : [q];
		if (opts.mode == 'remote'){
			_setValues(qq);
			request(target, null, {q:q}, true);
		} else {
			var panel = $(target).combo('panel');
			panel.find('div.combobox-item-selected,div.combobox-item-hover').removeClass('combobox-item-selected combobox-item-hover');
			panel.find('div.combobox-item,div.combobox-group').hide();
			var data = state.data;
			var vv = [];
			$.map(qq, function(q){
				q = $.trim(q);
				var value = q;
				var group = undefined;
				for(var i=0; i<data.length; i++){
					var row = data[i];
					if (opts.filter.call(target, q, row)){
						var v = row[opts.valueField];
						var s = row[opts.textField];
						var g = row[opts.groupField];
						var item = opts.finder.getEl(target, v).show();
						if (s.toLowerCase() == q.toLowerCase()){
							value = v;
							item.addClass('combobox-item-selected');
						}
						if (opts.groupField && group != g){
							$('#'+state.groupIdPrefix+'_'+$.inArray(g, state.groups)).show();
							group = g;
						}
					}
				}
				vv.push(value);
			});
			_setValues(vv);
		}
		function _setValues(vv){
			setValues(target, opts.multiple ? (q?vv:[]) : vv, true, q && !opts.autoComplete);
		}
	}
	
	function doEnter(target) {
		var t = $(target);
		var opts = t.combobox('options');
		var panel = t.combobox('panel');
		var item = panel.children('div.combobox-item-hover');
		/* 面板展开时，阻止上下键冒泡 start */
		if(panel.is(':hidden')) return false;
		/* 面板展开时，阻止上下键冒泡 end */
		if (item.length) {
			var row = opts.finder.getRow(target, item);
			var value = row[opts.valueField];
			if (opts.multiple) {
				if (item.hasClass('combobox-item-selected')) {
					t.combobox('unselect', value);
				} else {
					t.combobox('select', value);
				}
			} else {
				t.combobox('select', value);
			}
		}
		var vv = [];
		$.map(t.combobox('getValues'), function(v) {
			if (getRowIndex(target, v) >= 0) {
				vv.push(v);
			}
		});
		t.combobox('setValues', vv);
		if (!opts.multiple) {
			t.combobox('hidePanel');
		}
		return true;
	}

	/**
	 * scroll panel to display the specified item
	 */
	function scrollTo(target, value) {
		var opts = $.data(target, 'combobox').options;
		var panel = $(target).combo('panel');
		var item = opts.finder.getEl(target, value);
		if (item.length) {
			if (item.position().top <= 0) {
				var h = panel.scrollTop() + item.position().top;
				panel.scrollTop(h);
			} else if (item.position().top + item.outerHeight() > panel
					.height()) {
				var h = panel.scrollTop() + item.position().top
						+ item.outerHeight() - panel.height();
				panel.scrollTop(h);
			}
		}
	}
	
	function getRowIndex(target, value) {
		var state = $.data(target, 'combobox');
		var opts = state.options;
		var data = state.data;
		for ( var i = 0; i < data.length; i++) {
			if (data[i][opts.valueField] == value) {
				return i;
			}
		}
		return -1;
	}
	
	$.fn.combobox.methods = $.extend({}, $.fn.combobox.methods, {
		setValues: function(jq, values){
			return jq.each(function(){
				setValues(this, values);
			});
		},
		setValue: function(jq, value){
			return jq.each(function(){
				setValues(this, [value]);
			});
		}
	});
	
	/*阻止，上，下，enter，三个键盘输入冒泡，注意enter的浏览器默认事件在combo中已被禁制
	 *当然也可以对combo直接阻止冒泡，在子类做更加符合业务，毕竟combo只是个框架*/
	$.extend($.fn.combobox.defaults.keyHandler, {
		up : function(e) {// 38
			if (nav(this, 'prev'))
				e.stopPropagation();
			e.preventDefault();
		},
		down : function(e) {// 40
			if (nav(this, 'next'))
				e.stopPropagation();
			e.preventDefault();
		},
		enter : function(e) {// 13
			/*对于combo控件，enter在面板展开时表示选择功能， 
			 *阻止冒泡 若要隐藏面板可使用Esc与Tab，未阻止冒泡*/
			if (doEnter(this))
				e.stopPropagation();
		},
		query: function(q,e){doQuery(this, q)}
	});
	
	$.fn.combobox.defaults.filter = function(q,row){
		var opts=$(this).combobox("options");
		//将combobox下拉查询转化为小写再作比较
		return String(row[opts.textField]||"").toLowerCase().indexOf(q.toLowerCase())>=0;
	};
})(jQuery);

/**
 * combogrid
 * @param $
 */
(function($) {
	$.fn.combogrid.defaults.filter = function(q,row){
		//var opts=$(this).combogrid("options");
		//将combogrid下拉查询转化为小写再作比较
		var flag = false;
		for(var key in row) {
			var tmp = String(row[key]||"").toLowerCase().indexOf(q.toLowerCase())>=0;
			flag = flag || tmp;
		}
		return flag;
	};
})(jQuery);

/**
 * 扩展datagrid编辑器，增加my97datepicker支持
 */
(function($){
	$.extend($.fn.datagrid.defaults.editors, {
		my97 : {
			init : function(container, options) {
				var dateFmt = (options && options.dateFmt) || "yyyy-MM-dd";
				var input = null;
				if(options && options.readonly) {
					input = $('<input class="Idate"/>').appendTo(container);
					input.attr("readonly", "readonly");
				} else {
					input = $('<input class="Idate Wdate" onfocus="WdatePicker({dateFmt:\'' + dateFmt + '\'' 
						+ (options.minDate && options.minDate != '' ? ',minDate:\'' + options.minDate + '\'' : '')
						+ (options.maxDate && options.maxDate != '' ? ',maxDate:\'' + options.maxDate + '\'' : '')
						+ '});" />').appendTo(container);
				}
				if(options && options["onkeydown"]) { //加入回车事件支持
					input.bind("keydown", options["onkeydown"]);
				}
				input.data({"dateFmt":dateFmt});
				//var option = $.extend({}, options);
				//input.validatebox(option);
				return input;
			},
			getValue : function(target) {
				return $(target).val();
			},
			setValue : function(target, value) {
				if(value) {
					var filter = "[0-9]{4}-[0-9]{2}-[0-9]{2}\\s[0-9]{2}:[0-9]{2}:[0-9]{2}";
					if((new RegExp(filter)).test(value)) {//若数据类型为datetime第一次编辑，数据库标准时间格式，再次编辑时时间格式可能发生改变
						var dateFmt = target.data("dateFmt");
						var xd = new XDate(value);
						$(target).val(xd.toString(dateFmt));
					} else {
						$(target).val(value);
					}
				} else {
					$(target).val(value);
				}
			},
			resize : function(target, width) {
				var input = $(target);
				if(!$.boxModel&&$.browser.msie){
					input.width(width);
				}else{
					input.width(width-(input.outerWidth()-input.width()));
				}
			},destroy: function(target){
				if($dp && $dp.hide) {
					$dp.hide();
				}
				$(target).remove();
			}
		}
	});
})(jQuery);

/**扩展datagrid编辑器，增加combo单选支持*/
(function($){
	$.extend($.fn.datagrid.defaults.editors, {
		comboradio : {
			init : function(container, options) {
				var sel = $('<input/>').appendTo(container);
				sel.comboradio(options);
				return sel;
			},
			destroy : function(target) {
				$(target).comboradio('destroy');
			},
			getValue : function(target) {
				return $(target).comboradio('getValue');
			},
			setValue : function(target, value) {
				$(target).comboradio('setValue', value);
			},
			resize : function(target, width) {
				$(target).comboradio('resize', width);
			}
		}
	});
})(jQuery);

/** 扩展datagrid编辑器，增加combo多选支持 */
(function($){
	$.extend($.fn.datagrid.defaults.editors, {
		combocheck : {
			init : function(container, options) {
				var sel = $('<input/>').appendTo(container);
				sel.combocheck(options);
				return sel;
			},
			destroy : function(target) {
				$(target).combocheck('destroy');
			},
			getValue : function(target) {
				var values = $(target).combocheck('getValues');
				if ($.isArray(values)) {
					return values.join(",");
				} else {
					return values;
				}
			},
			setValue : function(target, value) {
				if (value) {
					var values = String(value).split(",");
					$(target).combocheck('setValues', values);
				} else {
					$(target).combocheck('setValues', []);
				}
			},
			resize : function(target, width) {
				$(target).combocheck('resize', width);
			}
		}
	});
})(jQuery);

/**
 * 扩展datagrid编辑器，增加combogrid支持
 * 
 */
(function($){
	$.extend($.fn.datagrid.defaults.editors, {
		combogrid : {
			init : function(container, options) {
				var inp = $('<input type="text" />').appendTo(container);
				$.extend(options, {
					/*onClickRow : function(rowIndex, rowData) {
						var selRows = inp.combogrid("grid").datagrid(
								"getSelections");
						if ($.inArray(rowData, selRows) >= 0) {
							inp.combogrid("grid").datagrid("unselectRow",
									rowIndex);
						} else {
							inp.combogrid("grid").datagrid("selectRow",
									rowIndex);
						}
					}*/
				});
				var cg = inp.combogrid(options);
				//cg.combogrid("grid").datagrid("loadData", options.data);
				return cg;
			},
			destroy : function(target) {
				$(target).combogrid('destroy');
			},
			getValue : function(target) {
				var values = $(target).combogrid('getValues');
				if ($.isArray(values)) {
					return values.join(",");
				} else {
					return values;
				}
			},
			setValue : function(target, value) {
				if (value != undefined && value != null) {
					var values = String(value).split(",");
					if ($.isArray(values)) {
						$(target).combogrid('setValues', values);
					} else {
						$(target).combogrid('setValue', value);
					}
				}
			},
			resize : function(target, width) {
				$(target).combogrid('resize', width);
			}
		}
	});
})(jQuery);

/** 
 * 扩展datagrid编辑器，增加button支持
 */
(function($){
	$.extend($.fn.datagrid.defaults.editors, {
		button : {
			init : function(container, options) {
				var inp = $('<input type="text" />').appendTo(container);

				$.extend(options, {
					// 多选也支持
					multiple : true,
					onClickRow : function(rowIndex, rowData) {
						var selRows = inp.combogrid("grid").datagrid(
								"getSelections");
						if ($.inArray(rowData, selRows) >= 0) {
							inp.combogrid("grid").datagrid("unselectRow",
									rowIndex);
						} else {
							inp.combogrid("grid").datagrid("selectRow",
									rowIndex);
						}
					}

				});
				var cg = inp.combogrid(options);
				cg.combogrid("grid").datagrid("loadData", options.data);
				return cg;
			},
			destroy : function(target) {
				$(target).combogrid('destroy');
			},
			getValue : function(target) {
				var values = $(target).combogrid('getValues');
				if ($.isArray(values)) {
					return values.join(",");
				} else {
					return values;
				}
			},
			setValue : function(target, value) {
				if (value != undefined && value != null) {
					var values = String(value).split(",");
					if ($.isArray(values)) {
						$(target).combogrid('setValues', values);
					} else {
						$(target).combogrid('setValue', value);
					}
				}
			},
			resize : function(target, width) {
				$(target).combogrid('resize', width);
			}
		}
	});
})(jQuery);

/**
 * 扩展EasyUI的validatebox验证方法
 * 
 */
(function($){
	$.extend($.fn.validatebox.defaults.rules, {
		equalTo : {
			validator : function(value, param) {
				return $(param[0]).val() == value;
			},
			message : '两次输入的密码不一致'
		}

	});

	/**
	 * 扩展EasyUI的验证方法，验证手机号
	 * 
	 */
	$.extend($.fn.validatebox.defaults.rules, {
		mobile : {
			validator : function(value, param) {
				return /^([1-9][0-9][0-9]|15[0|1|2|3|6|7|8|9]|18[6|8|9])\d{8}$/
						.test(value);
			},
			message : '请输入正确的11位手机号码.格式:13120002221'
		},
		postcode : {
			validator : function(value, param) {
				return /^\d{6}$/.test(value);
			},
			message : '请输入正确的6位邮政编码'
		}
	});

	/**
	 * 扩展EasyUI的验证方法，校验唯一性
	 * 
	 */
	$.extend($.fn.validatebox.defaults.rules, {
		unique : {
			validator : function(value, param) {
				var flag = true;
				/*
				 * if(!value) { return flag; }
				 */
				var url = param[0];
				var key = param[1];
				var id = $("#id").val();
				var data = {};
				data["id"] = id;
				if (param.length >= 3) {
					var field = param[2];
					data[key] = jwpf.getFormVal(field);
				} else {
					data[key] = value;
				}
				if (data[key] !== undefined && data[key] !== null
						&& data[key] !== "") {
					var options = {
						url : url,
						data : data,
						async : false,
						success : function(data) {
							if (data.msg) {
								flag = true;
							} else {
								flag = false;
							}
						}
					};
					fnFormAjaxWithJson(options, true);
				}
				return flag;
			},
			message : '该值已存在，请确保唯一性'
		}
	});

	/**
	 * 扩展EasyUI的验证方法，校验唯一性
	 * 
	 */
	$.extend($.fn.validatebox.defaults.rules, {
		uniqueSub : {
			validator : function(value, param, obj) {
				var flag = true;
				if (!value) {
					return flag;
				}
				var url = param[0];
				var key = param[1];
				var tableKey = param[2];
				var idAttr = param[3];
				var rowIndex = $(this).closest("td[field]").parent().attr(
						"datagrid-row-index");
				rowIndex = parseInt(rowIndex);
				var rows = $("#" + tableKey).datagrid('getRows');
				var row = rows[rowIndex];
				var data = {};
				data["id"] = row[idAttr];
				data[key] = value;
				if (param.length >= 5) {
					data["masterId"] = $("#id").val();
				}
				var options = {
					url : url,
					data : data,
					async : false,
					success : function(data) {
						if (data.msg) {
							flag = true;
						} else {
							flag = false;
						}
					}
				};
				fnFormAjaxWithJson(options, true);
				return flag;
			},
			message : '该值已存在，请确保唯一性'
		}
	});

	/**
	 * 扩展EasyUI的验证方法，验证传真
	 * 
	 */
	$.extend($.fn.validatebox.defaults.rules, {
		faxno : {// 验证传真
			validator : function(value) {
				return /^((\(\d{2,3}\))|(\d{3}\-))?(\(0\d{2,3}\)|0\d{2,3}-)?[1-9]\d{6,7}(\-\d{1,4})?$/i
						.test(value);
			},
			message : '传真号码不正确'
		}
	});

	/**
	 * 多重校验规则
	 */
	$.extend($.fn.validatebox.defaults.rules, {
		multiple : {
			validator : function(value, vtypes) {
				var returnFlag = true;
				var opts = $.fn.validatebox.defaults;
				for ( var i = 0; i < vtypes.length; i++) {
					var methodinfo = /([a-zA-Z_]+)(.*)/.exec(vtypes[i]);
					var rule = opts.rules[methodinfo[1]];
					if (value && rule) {
						var parame = eval(methodinfo[2]);
						if (!rule["validator"](value, parame)) {
							returnFlag = false;
							this.message = rule.message;
							break;
						}
					}
				}
				return returnFlag;
			},
			message : ''
		}
	});
})(jQuery);

/**
 * 扩展datagrid编辑器，增加combotree的keyHandler支持
 */
(function($){
	$.fn.getComboTreeData = function(root, dataArr) {
		for ( var k = 0; k < root.length; k++) {
			dataArr.push(root[k]);
			var child = $(this).tree('getChildren', root[k].target);
			if (child && child.length > 0) {
				$(this).getTreeData(child, dataArr);
			}
		}
	};
	$.fn._combotree = function(arr, treeData) {
		var panel = $(this).combo("panel");
		panel.find("div.tree-node-selected").removeClass("tree-node-selected");
		var vv = [], ss = [];
		for ( var i = 0; i < arr.length; i++) {
			var v = arr[i];
			var s = v;
			for ( var j = 0; j < treeData.length; j++) {
				if (treeData[j].text == v) {
					s = treeData[j].id;
					break;
				}
			}
			vv.push(v);
			ss.push(s);
		}
		$(this).combo("setValue", vv);
	};
	$.extend($.fn.combotree.defaults, {
		keyHandler : {
			up : function() {
				var _f = $.data(this, "combotree").options;
				var _10 = $.data(this, "combotree").tree;
				var panel = $(this).combo('panel');
				var divs = panel.find("div.tree-node");
				var vv = [], ss = [];
				var _12 = _10.tree("getSelected");
				if (_12) {
					var v = _12.id;
					v = new String(v);
					for ( var i = 0; i < divs.length; i++) {
						var dv = $(divs[i]).attr("node-id");
						if (dv == v) {
							if (divs[i - 1]) {
								v = $(divs[i - 1]).attr("node-id");
								var _18 = _10.tree("find", v);
								if (_18) {
									var s = _18.text;
									_10.tree("select", _18.target);
									vv.push(v);
									ss.push(s);
									$(this).combo("setValue", vv).combo(
											"setText", ss.join(_f.separator));
								}
							}
							break;
						}
					}
				} else {
					var _12 = $(divs[0]);
					var v = _12.attr("node-id");
					var _18 = _10.tree("find", v);
					if (_18) {
						var s = _18.text;
						_10.tree("select", _18.target);
						vv.push(v);
						ss.push(s);
						$(this).combo("setValue", vv).combo("setText",
								ss.join(_f.separator));
					}
				}
			},
			down : function() {
				var _f = $.data(this, "combotree").options;
				var _10 = $.data(this, "combotree").tree;
				var panel = $(this).combo('panel');
				var divs = panel.find("div.tree-node");
				var vv = [], ss = [];
				var _12 = _10.tree("getSelected");
				if (_12) {
					var v = _12.id;
					v = new String(v);
					for ( var i = 0; i < divs.length; i++) {
						var dv = $(divs[i]).attr("node-id");
						if (dv == v) {
							if (divs[i + 1]) {
								v = $(divs[i + 1]).attr("node-id");
								var _18 = _10.tree("find", v);
								if (_18) {
									var s = _18.text;
									_10.tree("select", _18.target);
									vv.push(v);
									ss.push(s);
									$(this).combo("setValue", vv).combo(
											"setText", ss.join(_f.separator));
								}
							}
							break;
						}
					}
				} else {
					var _12 = $(divs[0]);
					var v = _12.attr("node-id");
					var _18 = _10.tree("find", v);
					if (_18) {
						var s = _18.text;
						_10.tree("select", _18.target);
						vv.push(v);
						ss.push(s);
						$(this).combo("setValue", vv).combo("setText",
								ss.join(_f.separator));
					}
				}
			},
			enter : function() {
			},
			query : function(q) {
				var opts = $.data(this, "combotree").options;
				var panel = $(this).combo("panel");
				var treeObj = $(this).combotree("tree");
				var treeData = [];
				var roots = treeObj.tree("getRoots");
				$(this).getComboTreeData(roots, treeData);

				$(this)._combotree([ q ], treeData);

				panel.find("div.tree-node").hide();
				for ( var i = 0; i < treeData.length; i++) {
					var bl = treeData[i].text.indexOf(q) >= 0;
					if (bl) {
						var v = treeData[i].id;
						var s = treeData[i].text;
						var div = panel
								.find("div.tree-node[node-id=" + v + "]");
						div.show();
						if (s == q) {
							$(this)._combotree([ q ], treeData);
							div.addClass("tree-node-selected");
						}
					}
				}
			}
		}
	});
})(jQuery);

/**
 * 扩展combo编辑器，增加ComboRadio支持
 */
(function($) {

	$.fn.comboradio = function(options, param) {// 初始化方法
		if (typeof options == 'string') {
			var opt = $.fn.comboradio.methods[options];
			if (opt) {
				return opt(this, param);
			} else {
				return this.combo(options, param);
			}
		}
		options = options || {};
		options.multiple = false;
		return this.each(function() {
			var state = $.data(this, "comboradio");
			if (state) {
				$.extend(state.options, options);
			} else {
				state = {
					options : $.extend({}, $.fn.comboradio.defaults,$.fn.comboradio.parseOptions(this),options)
				};
				$.data(this, "comboradio", state);
			}
			var tag = $(this);
			tag.addClass("comboradio-f");
			tag.combo(state.options);// ??? 初始化继承combo
			var panel = $(this).combo("panel");
			var divs = $('<div></div>').appendTo(panel);
			var input = $(
				'<input type="text" placeholder="输入关键字查询" class="_chaxun" style="border-width:0px 0px 1px 0px;width:'
						+ (state.options.width - 2) + 'px"/>')
				.appendTo(divs);
			input.width(state.options.width - 6);
			var data = state.options.data;
			var valueField = state.options.valueField;
			var textField = state.options.textField;
			var id = $(this).attr("id");
			if (data && data.length) {
				var str = "";
				$.each(data, function(k, v) {
					str += "<div class='comboradio-item' ><input name ='"
							+ id
							+ "' type='radio' value='"
							+ v[valueField]
							+ "'/>"
							+ "<span>"
							+ v[textField]
							+ "</span>" + "</div>";
				});
				divs.append(str);
				divs.appendTo(panel);

				$(".comboradio-item", panel)
				.hover(function() {
					$(this).addClass("combobox-item-hover");
				}, function() {
					$(this).removeClass("combobox-item-hover");
				})
				.find("input:radio")
				.click(function() {
					var vv = tag.combo('getValue');
					var input = panel.find("input:radio[value='" + vv + "']");
					if (input) {
						var ss = input.next('span').text();
						var div = input.parent();

						var v = $(this).val();
						var s = $(this).next('span').text();
						var div2 = $(this).parent();
						if (vv == v) {
							if (div.attr("class").indexOf("combobox-item-selected") > -1) {
								div.children("input").attr("checked",false);
								div.removeClass("combobox-item-selected");
								tag.combo('setValue', "").combo('setText', "");
							} else {
								div.addClass("combobox-item-selected");
								tag.combo('setValue', vv).combo('setText', ss);
							}
						} else {
							div2.addClass("combobox-item-selected");
							div.removeClass("combobox-item-selected");
							tag.combo('setValue', v).combo('setText', s);
						}
					}

				});
			}
			input.keyup(function() {
				var text = $(this).val();
				$(this).nextAll().each(function() {
					if ($(this).children("span").text()
							.indexOf(text) > -1) {
						$(this).show();
					} else {
						$(this).hide();
					}
				});
			});
		});

	};

	$.fn.comboradio.parseOptions = function(target) {
		var t = $(target);
		return $.extend({}, $.fn.combo.parseOptions(target), {
			valueField : t.attr("valueField"),
			textField : t.attr("textField"),
			mode : t.attr("mode"),
			method : (t.attr("method") ? t.attr("method") : undefined),
			url : t.attr("url")
		});
	};

	function _radio(obj, arr) {
		var panel = $(obj).combo("panel");
		var opts = $.data(obj, "comboradio").options;
		var allData = opts.data;
		panel.find("div.combobox-item-selected").removeClass(
				"combobox-item-selected");
		var vv = [], ss = [];
		for ( var i = 0; i < arr.length; i++) {
			var v = arr[i];
			var s = v;
			for ( var j = 0; j < allData.length; j++) {
				if (allData[j][opts.valueField] == v) {
					s = allData[j][opts.textField];
					break;
				}
			}
			vv.push(v);
			ss.push(s);
			panel.find("input:radio[value='" + v + "']").parent().addClass(
					"combobox-item-selected");
		}
		$(this).combo("setValue", vv);
	}
	$.fn.comboradio.defaults = $.extend({}, $.fn.combo.defaults, {// 属性和事件
		editable : false,
		valueField : "value",
		textField : "text",
		mode : "local",
		method : "post",
		url : null,
		data : null,
		keyHandler : {
			up : function() {
				var panel = $(this).combo('panel');
				var div = panel.find("div.combobox-item-selected");
				if (div && div.length > 0) {
					var divPrev = div.prev("div.comboradio-item");
					if (divPrev && divPrev.length > 0) {
						var input = divPrev.find("input:radio");
						input.trigger("click");
					}
				} else {
					var divs = panel.find("div.comboradio-item");
					var input = $(divs[0]).find("input:radio");
					input.trigger("click");
				}
			},
			down : function() {
				var panel = $(this).combo('panel');
				var div = panel.find("div.combobox-item-selected");
				if (div && div.length > 0) {
					var divNext = div.next("div.comboradio-item");
					if (divNext && divNext.length > 0) {
						var input = divNext.find("input:radio");
						input.trigger("click");
					}
				} else {
					var divs = panel.find("div.comboradio-item");
					var input = $(divs[0]).find("input:radio");
					input.trigger("click");
				}
			},
			enter : function() {
				var val = $(this).comboradio("getValue");
				$(this).comboradio("setValue", val);
				$(this).combo("hidePanel");
			},
			query : function(val) {
				var opts = $.data(this, "comboradio").options;
				var panel = $(this).combo("panel");
				var allData = opts.data;
				_radio(this, [ val ]);
				panel.find("div.comboradio-item").hide();
				for ( var i = 0; i < allData.length; i++) {
					var bl = allData[i][opts.textField].indexOf(val) >= 0;
					if (bl) {
						var v = allData[i][opts.valueField];
						var s = allData[i][opts.textField];
						var input = panel.find("input:radio[value='" + v
								+ "']");
						var div = input.parent();
						div.show();
						if (s == val) {
							_radio(this, [ val ]);
							div.addClass("combobox-item-selected");
							input.trigger("click");
						}
					}
				}
			}

		}
	});

	$.fn.comboradio.methods = {
		options : function(jq) {
			return $.data(jq[0], "comboradio").options;
		},
		getData : function(jq) {
			return $.data(jq[0], "comboradio").data;
		},
		setValue : function(jq, value) {
			return jq.each(function() {
				var panel = $(this).combo('panel');
				if (value != undefined && value != null) {
					var input = panel.find("input:radio[value='" + value
							+ "']");
					input.trigger("click");
				}
			});
		},
		getValue : function(target) {
			var value = $(target).combo('getValue');
			return value;
		},
		clear : function(jq) {
			return jq.each(function() {
				$(this).combo("clear");
				var p = $(this).combo("panel");
				p.find("div.combobox-item-selected").removeClass(
						"combobox-item-selected");
			});
		},
		destroy : function(jq) {
			return jq.each(function() {
				$(this).combo("hidePanel");
				$(this).remove();
			});
		},
		resize : function(jq, width) {
			jq.combo("panel").find("input._chaxun").width(width - 2);
			return jq.combo("resize", width);
		}
	};

})(jQuery);	

/**
 * 扩展ImageBox控件，
 * 子表图片控件没用直接调用此控件，但实现方式大致类似
 * param
 */
(function($) {
	$.fn.imagebox = function(options, param) {
		if(typeof options == 'string') {
			var opt = $.fn.imagebox.methods[options];
			if(opt) {
				return opt(this, param);
			} else {
				return this.imagebox(options, param);
			}
		}
		options = options || {};
		return this.each(function() {
			options = $.extend($.fn.imagebox.defaults, options);
			var $this = $(this);
			var w = $this.width();
			var h = $this.height();
			if (w && w >= 20) {
				options.width = w;
			}
			if (h && h >= 20) {
				options.height = h;
			}
			$.data(this, "imagebox", {"options":options});
			var imageName = $this.attr("id");
			var imgs = imageName + "Imgs";
			var src = imageName + "Src";
			var alter = imageName + "Alter";
			var upload = imageName + "Upload";
			var del = imageName + "Del";
			/*构造图片的显示html*/
			var imageHtml = "<div id='" + imgs + "' style='position:relative'>"
				+ "<img src='" + options.src
				//+ "http://127.0.0.1/jwpf/upload/gs-attach/image/20150107/20150107163608349.jpg"
				+ "' id='" + src + "' style='width:" + options.width + "px;height:" + options.height + "px;'/>"
				+ "<div id='" + alter + "' style='width:" + options.width + "px;height:20px;position:absolute;bottom:0px;"
				+ "visibility:hidden;background-color:#00a2d4;filter:alpha(opacity=50);-moz-opacity:0.5;-khtml-opacity:0.5;opacity:0.5'>"
				+ "<div style='position:relative;'><div id='" + upload + "' title='上传图片'"
				+ " style='width:18px;height:18px;position:absolute;left:0px;'>"
				+ "<input class='icon-add' style='width:18px;height:18px;background-color:transparent;border:0px;'>"
				+ "</div>"
				+ "<div title='删除图片' style='width:18px;height:18px;position:absolute;top:0px;right:0px;'>"
				+ "<input style='background-color:transparent;width:18px;height:18px;border:0px;outline:none;cursor:pointer'"
				+ " type='button' class='icon-remove' id='" + del + "' />"
				+ "</div></div></div></div>";
			$this.after(imageHtml);
			/*存放上传的图片的图片名字*/
			var inputHtml = "<input type='hidden' name='" + imageName + "'/>";
			$this.after(inputHtml);
			/*用webuploader插件初始化图片上传控件*/
			// 初始化Web Uploader
			var webuploader = WebUploader.create({
			    // 选完文件后，是否自动上传。
			    auto : true,
			    // swf文件路径
			    swf : __ctx + '/js/webuploader/Uploader.swf',
			    // 文件接收服务端。
			    server : __ctx + '/sys/attach/upload-file!input.action',
			    // 选择文件的按钮。可选。
			    // 内部根据当前运行是创建，可能是input元素，也可能是flash.
			    pick : '#' + upload,
			    // 只允许选择图片文件。
			    accept : {
			        title : 'Images',
			        extensions : 'gif,jpg,jpeg,bmp,png',
			        mimeTypes : 'image/*'
			    },
			    //fileVal : "filedata",
			    sendAsBinary : true
			});
			/*webuploader.on('fileQueued', function(file) {
				console.log(file);
				webuploader.makeThumb(file, function(error, _src) {
			        if(error) {
			            $img.replaceWith('<span>不能预览</span>');
			            return;
			        }
			        $("#" + src).attr('src', _src);
			    });
			});*/
			webuploader.on('uploadSuccess', function(file, path) {
				$("#" + src).attr('src', options.vPath+path.msg);
				$("input[name="+imageName+"]").val(path.msg);
				if(options.onAfterSetImage) {
					options.onAfterSetImage.call($this, path.msg);
				}
			});
			webuploader.on('uploadError', function(file, res) {
				alert("文件上传出现异常：" + res);
			});
			webuploader.on( 'error', function( type ) {
				alert("文件校验出现异常："+type);
			});
			/*为图片控件添加按钮显示事件*/
			var navigator_platform = navigator.platform;
			if(navigator_platform.indexOf('Win') == 0 || navigator_platform.indexOf('Mac') == 0 || navigator_platform == 'X11') {
				/*桌面端效果*/
				$("#" + imgs)
				.parents("td")
				.mouseout(function() {
					if("view" != operMethod) $("#" + alter).css({visibility : "hidden"});
				}).mouseover(function() {
					if("view" != operMethod) {
						var width = $(this).find("img").width();
						var btLayer = $("#" + alter);
						//btLayer.find("#"+upload).css("left", width/2-30);
						//btLayer.find("#"+del).parent().css("left", width/2+6);
						btLayer.find("#"+del).parent().css("right", width/4);
						btLayer.css({visibility : "visible"});
					}
				}).dblclick(function() {
					$("#" + src).gzoomExpand($(this).find("img").attr("src"));
				});
			} else {
				/*移动端效果*/
				if("view" != operMethod) {
					$("#" + alter)
					.css({visibility : "visible"})
					.children("div");
				} else {
					$("#tedit").click(function(){
						$("#" + alter)
						.css({visibility : "visible"})
						.children("div");
					});
				}
			}
			$("#" + del).click(function() {
				$("#" + src).removeAttr("src");
				$("input[name=" + imageName + "]").val("");
				if(options.onAfterSetImage) {
					options.onAfterSetImage.call($this, "");
				}
			});
			/*禁止$this提交字段内容，由hidden元素提交图片文件名*/
			$this.hide();
		});
	};
	
	$.fn.imagebox.methods = {
		options:function(jq){
			return $.data(jq[0],"imagebox").options;
		},
		getValue: function(target){
			var imgSrc = $(target).next().val();
			return imgSrc;
		},
		setValue: function(jq, val){
			return jq.each(function() {
				var value = val || "";
				/*将图片路径value值加入<input type='hidden' name='" + imageName+ "' />*/
				 $(this).next().val(value);
				 /*将img元素的src属性设置为图片路径value值*/
				 var opt = $(this).imagebox("options");
				 var divs = $(this).nextAll("div");
				 for(var i = 0;i<divs.length;i++){
						var img_img = $(divs[i]).find("img");
						if(img_img.length>0){
							if(value=="") {
								img_img.attr("src", "#");
							} else {
								img_img.attr("src", opt.vPath + value);
								//img_img.attr("src", "/jwpf/upload/gs-attach/" + value);
							}
						}
					}
			});
		},
		enable : function(jq){
			return jq.each(function() {
				var but_div = $(this).nextAll("div.file_upload_button");
				if(but_div.length > 0){
					 for(var i = 0;i<but_div.length;i++){
							$(but_div[i]).show();
						}	
				}
			});
		},
		disable : function(jq){
			return jq.each(function() {
				var but_div = $(this).nextAll("div.file_upload_button");
				if(but_div.length > 0){
					 for(var i = 0;i<but_div.length;i++){
							$(but_div[i]).hide();
						}	
				}
			});
		},
		resize: function(jq, width){
			return jq.each(function() {
				var divs = $(this).nextAll("div");
				 for(var i = 0;i<divs.length;i++){
					var input = $(divs[i]).find("img");
					if(input.length){
						if(!$.boxModel&&$.browser.msie){
							input.width(width);
						}else{
							input.width(width-(input.outerWidth()-input.width()));
						}
					}
				}
			});
		}
	};
	
	$.fn.imagebox.defaults = {
			src:null,
			width:100,
			height:100,
			vPath:null
	};
	
})(jQuery);

/**
 * 扩展DialogueWindow控件，
 * 继承 textbox
 */
(function($){
	
	var init = function(jq, opts) {
		if(!$(jq).attr('_isEditor')) {//主表字段编辑，互换ID和文本控件
			var id = $(jq).attr("name");
			var idText = id + "text";
			var hidTxtObj = $("#"+idText);
			if(hidTxtObj.length == 0) {//如果不存在则插入隐藏值
				hidTxtObj = $("<input type='hidden' id='" + idText + "'/>");
				hidTxtObj.insertBefore($(jq));
			}
			hidTxtObj.attr("name", id);
			//hidTxtObj.attr("id", id);
			//$(this).attr("id", idText);
			$(jq).attr("name", idText);
			//$(this).attr("forId", id);
		}
		$(jq).textbox($.extend(true, {
			icons : [ {
				iconCls : 'dialogue-window',
				handler : function(e) {
					create(e.data.target);
				}
			}]
		}, opts, $.fn.dialoguewindow.parseOptions));
	};
	
	var initBootstrap = function(jq) {
		var $wrap = $(jq),
			$prepend = $('<div class="input-group input-group-sm">' 
					 + '<input type="text" class="form-control read-only" readonly="true"/>'
					 + '<span class="input-group-btn">'
					 + '<a class="btn btn-default" role="button">'
					 + '<span class="glyphicon glyphicon-list"></span>'
					 + '</a></span></div>'),
			$wrapInput = $prepend.find("input"),
			$wrapBt = $prepend.find("a.btn");
		$wrap.addClass("hidden").hide();
		$prepend.insertBefore($wrap);
		var name = $wrap.attr("name");
		$wrapInput.attr("name", name + "text");
		$wrapInput.attr("placeholder", $wrap.attr("placeholder"));
		$wrapInput.attr("required", $wrap.attr("required"));
		$wrapBt.off("click").on("click", function(event) {
			var state = $wrap.data("dialoguewindow");
			state["data"]["id"] = $wrap.val();//默认值
			create(jq);
		});
	};
	
	/* 创建查询窗口 */
	function create(target) {
		var state = $.data(target, 'dialoguewindow');
		var options = state.options;
		var data = $.fn.dialoguewindow.methods["getValue"]($(target));//state.data;/*存放key与caption的数据，一则方便获取，二则子表中没必要存在key的隐藏input*/
		var url = options.url || "/sys/dataFilter/dialogue-window-v2.action?entityName="
				+ options.entityName + "&style=" + options.style;
		/*控件的键值，即当前查询条件，若存在则将key作为查询条件直接查询
		因为目前数据加载未通过easyui.form，所以可能存在key的input中有值data中没值，
		现在将dialoguewindow，纳入form管理*/
		if(url.indexOf("?") == -1) {
			url = url + "?1=1";
		}
		if(options.multiple) {
			url = url + "&multiple=" + options.multiple;
		}
		var keyval = data.key;
		if (keyval) {
			url = url + "&key=" + keyval;
		}
		var qp = options["queryParams"];
		if(options["onSetQueryParam"]) {
			qp = $.extend(true, {}, qp, options["onSetQueryParam"].call(target, qp, options["rowData"], options["rowIndex"]));
		}
		if(qp && !$.isEmptyObject(qp)) {
			var fp = JSON.stringify(qp);
			url = url + "&queryParams=" + encodeURIComponent(fp);
		}
		/*打开表单窗口，方法在common.js中定义*/
		openFormWin({
			title : "查询  " + options.title,
			url : url,
			width : 800,
			height : 500,
			onAfterSure : function(win) {
				var newValue = win.getValue();
				if (newValue) {
					var oldValue = $.fn.dialoguewindow.methods["getValue"]($(target));//$(target).dialoguewindow("getValue");
					if (oldValue.caption != newValue.caption || oldValue.key != newValue.key) {
						$(target).dialoguewindow("setValue", newValue);
						var opt = $.fn.dialoguewindow.methods["options"](target);
						if(opt && opt.onChange) {
							opt.onChange.call(target, newValue, oldValue);
						}
					}
				} else {
					$(target).dialoguewindow("setValue", newValue);
				}
				return true;
			}
		});
	}
	
	var getRemoteValue = function(jq, value) {
		var opt = $(jq).data("dialoguewindow").options;
		var keyMap = opt["keyMap"];
		var idKey = keyMap["idKey"];
		var textKey = keyMap["textKey"];
		var queryParam = {};
		queryParam[opt["filterParam"]] = value;
		if(opt["onSetQueryParam"]) {
			queryParam = $.extend(true, {}, queryParam, opt["onSetQueryParam"].call(jq, queryParam, opt["rowData"], opt["rowIndex"]));
		}
		var idArr = [];
		var nameArr = [];
		var ajaxOpt = {
				url : opt["filterUrl"],
				data : queryParam,
				async : false,
				success : function(data) {
					var result = $.isArray(data) ? data : data.msg;
					if (result) {
						$.each(result, function(key, obj){
							idArr.push(obj[idKey]);
							nameArr.push(obj[textKey] || obj["name"]);
						});
					}
				}
		};
		fnFormAjaxWithJson(ajaxOpt);
		var ids = idArr.join(",") || value;
		var texts = nameArr.join(",") || value;
		return {"id":ids,"text":texts,"key":ids,"caption":texts};
	};
	
	$.fn.dialoguewindow = function(options, param) {
		if (typeof options == 'string') {
			var method = $.fn.dialoguewindow.methods[options];
			if (method) {
				return method(this, param);
			} else {
				return {};//this.textbox(options, param);
			}
		}
		options = options || {};
		return this.each(function() {
			var state = $.data(this, 'dialoguewindow');
			if (state) {
				$.extend(true, state.options, options);
				//$.extend(state, {options: options, data: {}});
				//$(this).textbox($.extend({}, state.options, $.fn.dialoguewindow.parseOptions));
			} else {
				var opts = $.extend(true, {}, $.fn.dialoguewindow.defaults, options);
				$.data(this, 'dialoguewindow', {
					options : opts,
					data : {}
				});
				if(opts.theme == "bootstrap") {
					initBootstrap(this);
				} else {
					init(this, opts);
				}
			}
		});
	};

	$.fn.dialoguewindow.methods = {
		options : function(jq) {
			/*options部分属性，存在于textbox的data中，
			 *项目使用dialoguewindow控件获取options时已进行同步，
			 *开发员在修改dialoguewindow控件时，注意属性所在位置*/
			/*var copts = jq.textbox('options');
			return $.extend($.data(jq[0], 'dialoguewindow').options, {
				disabled : copts.disabled,
				readonly : copts.readonly
			});*/
			return $(jq).data("dialoguewindow").options;
		},
		getValue : function(jq) {
			var data = $.data(jq[0], 'dialoguewindow');
			if(!data["data"] || $.isEmptyObject(data["data"])) {
				var opt = data["options"];
				if(opt.theme == "bootstrap") {
					var id = jq.val();
					var text = jq.prev().find("input").val();
					data["data"] = {"key":id,"caption":text,"id":id,"text":text};
				} else {
					var id = $("#" + jq.attr("id") + "text").val();
					var text = jq.textbox("getValue");
					data["data"] = {"key":id,"caption":text,"id":id,"text":text};
				}
			}
			return data["data"];
		},
		setValue : function(jq, val) {
			/*若主子表存在同样id的字段，此控件存在误选的可能，解决方法
			 *子表的dialoguewindow在init时加上元素属性_isEditor=true*/
			if(val) {
				if(!$.isPlainObject(val)) {
					val = getRemoteValue(jq, val);
				}
			} else {
				val = {"key":"","caption":"","id":"","text":""};
			}
			var opt = $.fn.dialoguewindow.methods["options"](jq);
			if(opt.theme == "bootstrap") {
				jq.val(val.id);
				jq.prev().find("input").val(val.text);
			} else {
				if(!jq.attr('_isEditor')) {
					$("#" + jq.attr("id") + "text").val(val.key);
				}
				jq.textbox("setValue", val.caption);
			}
			val["id"] = val.key;
			val["text"] = val.caption;
			$.data(jq[0], 'dialoguewindow').data = val;
		},
		setQueryParam : function(jq, param) {
			var opt = $.fn.dialoguewindow.methods["options"](jq);
			$.extend(opt["queryParams"], param);
		},
		enable : function(jq) {
			return jq.each(function() {
				var opt = $(this).data("dialoguewindow").options;
				if(opt.theme == "bootstrap") {
					$(this).prev().find("input:first").prop("readonly",false);
					$(this).prev().find("a.btn").prop("disabled",false);
				} else {
					$(this).textbox("enable");
				}
			});
		},
		disable : function(jq) {
			return jq.each(function() {
				var opt = $(this).data("dialoguewindow").options;
				if(opt.theme == "bootstrap") {
					$(this).prev().find("input:first").prop("readonly",true);
					$(this).prev().find("a.btn").prop("disabled",true);
				} else {
					$(this).textbox("disable");
				}
			});
		}
	};

	$.fn.dialoguewindow.parseOptions = {
		/*不允许通过属性设置可编辑，否则会出现键值对应不上，onchange事件回调不及时的问题*/
		editable : false,
		/*阻止TextBox回调设计器中的onChange*/
		onChange : function(newValue, oldValue) {
		}
	};

	$.fn.dialoguewindow.defaults = $.extend({}, $.fn.textbox.defaults, {
		title : '',//查询窗口title
		url : "",//查询url
		entityName : '',//sql映射键
		style : 'module',//数据源
		theme : 'easyui',//显示样式
		queryParams: {},//查询参数
		filterUrl:"",//设值url
		filterParam:"",//ID对应过滤属性，如：filter_INL_ID
		keyMap:{"idKey":"id","textKey":"text"},//结果取值Map
		onSetQueryParam:null //设置查询参数方法
	});
})(jQuery);

/**
 * 扩展ProcessBar和NumberSpinner控件
 * param
 */
(function($){
	$.fn.processbarSpinner = function(options, param) {
		if (typeof options == 'string') {
			var opt = $.fn.processbarSpinner.methods[options];
			if (opt) {
				return opt(this, param);
			} else {
				return this.processbarSpinner(options, param);
			}
		}
		options = options || {};
		return this.each(function() {
			options = $.extend($.fn.processbarSpinner.defaults, options);
			var id = $(this).attr("id");
			var pbId = "pb_" + id;
			var w = $(this).width();
			var h = $(this).height();
			if (w && w >= 100) {
				options.width = w;
			}
			if (h && h >= 100) {
				options.height = h;
			}
			$.data(this, "processbarSpinner", {"options":options});
			$(this).wrap("<div/>");
			$(this).before("<div style='float:left;padding:8px 0px 0px 2px;'><div id='" + pbId + "'/></div>");
			$(this).after("<div style='clear:both;'></div>");
			$("#"+pbId).progressbar({
				width:options.width
			});
			$(this).css("height",18);
			$(this).wrap("<div style='float:left;padding:5px;'/>");
			$(this).numberspinner({
				min:0,
				max:100,
				value:0,
				width:50,
				onSpinUp:function() {
					var value = $(this).numberspinner("getValue");
					$("#"+pbId).progressbar("setValue", value);
				},
				onSpinDown:function() {
					var value = $(this).numberspinner("getValue");
					$("#"+pbId).progressbar("setValue", value);
				}
			});
		});
	};
	
	$.fn.processbarSpinner.methods = {
		options:function(jq){
			return $.data(jq[0],"processbarSpinner").options;
		},
		getValue: function(target){
			var val = $(target).numberspinner("getValue");
			return val;
		},
		setValue: function(jq, value){
			return jq.each(function() {
				$(this).numberspinner("setValue", value);
				var id = $(this).attr("id");
				$("#pb_"+id).progressbar("setValue", value);
			});
		},
		enable : function(jq){
			return jq.each(function() {
				$(this).numberspinner("enable");
			});
		},
		disable : function(jq){
			return jq.each(function() {
				$(this).numberspinner("disable");
			});
		},
		resize: function(jq, width){
			return jq.each(function() {
				var input = $(this);
				if(!$.boxModel&&$.browser.msie){
					input.width(width);
				}else{
					input.width(width-(input.outerWidth()-input.width()));
				}
			});
		}
	};
	$.fn.processbarSpinner.defaults = {
			width:100,
			height:100
	};
})(jQuery);

/**
 * 修改datagrid编辑器
 */
(function($){
	
	$.extend($.fn.datagrid.defaults.view, {
		refreshRow : function(target, index) {
			this.updateRow.call(this, target, index, "isRefreshRow");
		},
		updateRow : function(target, index, row) {
			/**更新指定的行，param参数包含如下属性：
			index：要更新的行索引。
			row：新的行数据。*/
			var opts = $.data(target, "datagrid").options;
			var rows = $(target).datagrid("getRows");
			var oldcss = _css(index);
			if(!(typeof(row) == "string" && row == "isRefreshRow")) {
				//使updateRow方法，按照新的row数据更新行，不考虑原有数据
				//rows[index] = row;
				$.extend(rows[index],row);
			}
			var newcss = _css(index);
			var oldclass = oldcss.c;
			var newstyle = newcss.s;
			var newclass = "datagrid-row "
					+ (index % 2 && opts.striped ? "datagrid-row-alt " : " ")
					+ newcss.c;
			_changeRow.call(this, true);
			_changeRow.call(this, false);
			$(target).datagrid("fixRowHeight", index);
			
			function _css(index) {
				var css = opts.rowStyler ? opts.rowStyler.call(target, index, rows[index]) : "";
				var c = "";
				var s = "";
				if (typeof css == "string") {
					s = css;
				} else {
					if (css) {
						c = css["class"] || "";
						s = css["style"] || "";
					}
				}
				return {
					c : c,
					s : s
				};
			};
			
			/*为了合并单元格后的结束编辑操作正常进行，略微改动与翻译源码*/
			function _changeRow(isFrozen) {
				var columnFields = $(target).datagrid("getColumnFields", isFrozen);
				var tr = opts.finder.getTr(target, index, "body", (isFrozen ? 1 : 2));
				var checked = tr.find("div.datagrid-cell-check input:checkbox").is(":checked");
				var rowspan = {};
				/*在更新行元素之前，保存rowspan跟display属性 start*/
				tr.children().each(function() {
					rowspan[$(this).attr("field")] = {
						"rowspan" : $(this).attr("rowspan"),
						"display" : $(this).css("display")
					};
				});
				/*在更新行元素之前，保存rowspan跟display属性 end*/
				tr.html(this.renderRow.call(this, target, columnFields, isFrozen, index, rows[index]));
				tr.attr("style", newstyle).removeClass(oldclass).addClass(newclass);
				/*在更新行元素之前，设置rowspan跟display属性 start*/
				tr.children().each(function() {
					if (rowspan[$(this).attr("field")]) {
						$(this).attr("rowspan", rowspan[$(this).attr("field")].rowspan);
						if (rowspan[$(this).attr("field")].display === "none") {
							$(this).css({
								"display" : "none"
							});
						}
					}
				});
				/*在更新行元素之前，设置rowspan跟display属性 end*/
				if (checked) {
					tr.find("div.datagrid-cell-check input:checkbox")._propAttr("checked", true);
				}
			};
		}
	});
	
	/**
	 * 自动适应内容高度
	 * @param $
	 */
	(function($) {

		$.fn.autoTextarea = function(options) {

			var defaults = {

				maxHeight : null,// 文本框是否自动撑高，默认：null，不自动撑高；如果自动撑高必须输入数值，该值作为文本框自动撑高的最大高度

				minHeight : $(this).height()
			// 默认最小高度，也就是文本框最初的高度，当内容高度小于这个高度的时候，文本以这个高度显示

			};

			var opts = $.extend({}, defaults, options);

			return $(this)
					.each(
							function() {

								$(this)
										.bind(
												"paste cut keydown keyup focus blur",
												function() {

													var height, style = this.style;

													this.style.height = opts.minHeight
															+ 'px';

													if (this.scrollHeight > opts.minHeight) {

														if (opts.maxHeight
																&& this.scrollHeight > opts.maxHeight) {

															height = opts.maxHeight;

															style.overflowY = 'scroll';

														} else {

															height = this.scrollHeight;

															style.overflowY = 'hidden';

														}

														style.height = height
																+ 'px';
														// 触发datagrid重新设置高度
														var tr = $(this)
																.closest(
																		"tr[datagrid-row-index]");
														if (tr.length) {
															var dg = tr
																	.closest(
																			"div[class='datagrid-view']")
																	.find(
																			"table[id]");
															if (dg.length) {
																var dgId = dg
																		.attr("id");
																var rowIndex = tr
																		.attr("datagrid-row-index");
																$("#" + dgId)
																		.edatagrid(
																				"fixRowHeight",
																				parseInt(rowIndex));
															}
														}

													}

												});

							});

		};

	})(jQuery);
	
	$.fn.datagrid.defaults.editors.text.init = function(container, options) {
		var input = $("<input type=\"text\" class=\"datagrid-editable-input\">")
				.appendTo(container);
		if (options && options.readonly) {
			input.attr("readonly", "readonly");
		}
		if (options && options["onkeydown"]) { // 加入回车事件支持
			input.bind("keydown", options["onkeydown"]);
		}
		return input;
	};

	$.fn.datagrid.defaults.editors.textarea.init = function(container, options) {
		var input = $('<textarea class="datagrid-editable-input Itext"></textarea>')
				.appendTo(container);
		if (options && options.readonly) {
			input.attr("readonly", "readonly");
		}
		input.autoTextarea();
		input.bind('keydown', function(e) {
			if (e.ctrlKey && e.keyCode == 13) {
				/*
				 * var content = $(e.target).val(); content = content+'\n';
				 * $(e.target).val(content);
				 */
				$(e.target).insert({
					"text" : "\n"
				});
				return false;
			}
		});
		return input;
	};

	$.fn.datagrid.defaults.editors.validatebox.init = function(container, options) {
		var input = $("<input type=\"text\" class=\"datagrid-editable-input\">")
				.appendTo(container);
		if (options && options.readonly) {
			input.attr("readonly", "readonly");
		}
		input.validatebox(options);
		if (options && options["onkeydown"]) { // 加入回车事件支持
			input.bind("keydown", options["onkeydown"]);
		}
		return input;
	};

	$.fn.datagrid.defaults.editors.numberbox.init = function(container, options) {
		var _512 = $("<input type=\"text\" class=\"datagrid-editable-input\">")
				.appendTo(container);
		_512.numberbox(options);
		if (options && options["onkeydown"]) { // 加入回车事件支持
			_512.bind("keydown", options["onkeydown"]);
		}
		return _512;
	};
})(jQuery);

/**
 * 扩展combo编辑器，增加newradiobox支持
 */
(function($){
		
	$.fn.newradiobox = function(options, param){//初始化方法
		if (typeof options == 'string'){
			var opt=$.fn.newradiobox.methods[options];
			if(opt){
				return opt(this,param);
			}else{
				return this.combo(options,param);
			}
		}
		options = options || {};		
		options.multiple = false;
		return this.each(function(){
			var state=$.data(this,"newradiobox");
			if(state){
				$.extend(state.options,options);			
			}else{
				state = {options:$.extend({},$.fn.newradiobox.defaults,options)};
				$.data(this,"newradiobox",state);	
			}		
			var tag= $(this);
			tag.addClass("newradiobox-f");
			tag.combo(state.options);
			tag.combo("panel").hide();
			var divs =$('<div class="easyui-newradiobox" style="width:100%;"></div>');
			tag.after(divs);
			tag.removeAttr("name");
			tag.hide();
			divs.next("span.combo").hide();
			var data =  state.options.data;
			var valueField =  state.options.valueField;
			var textField =  state.options.textField;		
			var id = $(this).attr("id");
			if(data && data.length){
				var str="";
				$.each(data,function(k,v){
					 str +="<input name='"+id+"1' type='radio' value='"+v[valueField]+"'/>"+v[textField] + "&nbsp;&nbsp;"; 				 						 
					});
					divs.append(str);
					
					divs.find("input:radio").click(function(){	
						
						   	var vv=tag.combo('getValue');
						   	
							var input = divs.find("input:radio[value='"+ vv+ "']");
							if(input){			
							var v = $(this).val();
							if(vv==v){
								tag.combo('setValue', vv);
							}else{
								tag.combo('setValue', v);	
							}
						}
										
					});
				   }	
			
			});
	
	};
	
	$.fn.newradiobox.defaults = $.extend({},$.fn.combo.defaults,{
		valueField:"value",
		textField:"text",
		mode:"local",
		method:"post",
		url:null,
		data:null,
		keyHandler:{
		}
	});
	
	$.fn.newradiobox.methods = {
		options:function(jq){
			return $.data(jq[0],"newradiobox").options;
		},
		getData:function(jq){
			return $.data(jq[0],"newradiobox").data;
		},
		setValue: function(jq, value){	
			return jq.each(function() {
			 	  var divs = $(this).next("div.easyui-newradiobox");
				  if(value!=undefined && value!=null) {									
					  var input = divs.find("input:radio[value='"+ value+ "']"); 
					  input.trigger("click");					  
				  }
			});
		  },
		getValue: function(target){		
			var value=$(target).combo('getValue');
			return value;	  
		},
		destroy: function(jq){
			return jq.each(function() {
				$(this).combo("hidePanel");
				$(this).remove(); 
			});
		}
	};

})(jQuery);

/**
 * 扩展combo编辑器，增加newcheckbox支持
 */
(function($){
	$.fn.newcheckbox = function(options, param) {// 初始化方法
		if (typeof options == 'string') {
			var opt = $.fn.newcheckbox.methods[options];
			if (opt) {
				return opt(this, param);
			} else {
				return this.combo(options, param);
			}
		}
		options = options || {};
		options.multiple = true;
		return this.each(function() {
			var state = $.data(this, "newcheckbox");
			if (state) {
				$.extend(state.options, options);
			} else {
				state = {
					options : $.extend({}, $.fn.newcheckbox.defaults,
							options)
				};
				$.data(this, "newcheckbox", state);
			}

			var tag = $(this);
			tag.addClass("newcheckbox-f");
			tag.combo(state.options);
			tag.combo("panel").hide();
			var divs = $("<div class='easyui-newcheckbox' style='width:100%;'></div>");
			tag.after(divs);
			tag.removeAttr("name");
			tag.hide();
			divs.next("span.combo").hide();
			var data = state.options.data;
			var valueField = state.options.valueField;
			var textField = state.options.textField;
			var id = $(this).attr("id");
			if (data && data.length) {
				var str = "";
				$.each(data, function(k, v) {
					str += "<input name ='" + id
							+ "1'  type='checkbox' value='"
							+ v[valueField] + "'/>" + "<span>"
							+ v[textField] + "</span>";
				});
				divs.append(str);
				divs.find("input:checkbox").click(function() {
					var vv = tag.combo("getValues");// 得到选中的值
					vv = $.map(vv, function(n) {
						return n == "" ? null : n;
					});
					var v = $(this).val();

					if ($.inArray(v, vv) >= 0) {
						vv = $.map(vv, function(n) {
							return n == v ? null : n;
						});
					} else {
						vv.push(v);
					}
					if (vv.length == 0) {
						vv = [ "" ];
						tag.combo('setValues', vv);
					} else {
						tag.combo('setValues', vv);
					}
				});
			}
		});
	};

	$.fn.newcheckbox.defaults = $.extend({}, $.fn.combo.defaults, {
		multiple : true,
		valueField : "value",
		textField : "text",
		mode : "local",
		method : "post",
		url : null,
		data : null,
		keyHandler : {}
	});

	$.fn.newcheckbox.methods = {
		options : function(jq) {
			return $.data(jq[0], "newcheckbox").options;
		},
		getData : function(jq) {
			return $.data(jq[0], "newcheckbox").data;
		},
		getValues : function(target) {
			var values = $(target).combo('getValues');
			return values;
		},
		getValue : function(target) {
			var values = $(target).combo('getValue');
			return values;
		},
		setValues : function(jq, value) {
			return jq.each(function() {
				if (value) {
					var opts = $.data(this, 'newcheckbox').options;
					value = $.isArray(value) ? value : String(value)
							.split(opts.separator);
					var options = $(this).newcheckbox("options");
					var divs = $(this).next("div.easyui-newcheckbox");
					var data = options.data;
					var vv = [];
					for ( var i = 0; i < value.length; i++) {
						var v = value[i];
						for ( var j = 0; j < data.length; j++) {
							if (data[j][options.valueField] == v) {
								var input = divs
										.find("input:checkbox[value='" + v
												+ "']");
								input.attr("checked", "checked");
								break;
							}
						}
						vv.push(v);
					}
					$(this).combo("setValues", vv);

				} else {
					$(this).combo("setValues", []);
				}
			});
		},
		setValue : function(jq, value) {
			return jq.each(function() {
				if ($.isArray(value)) {
					$(this).newcheckbox("setValues", value);
				} else {
					$(this).newcheckbox("setValues", [ value ]);
				}
			});
		}
	};
})(jQuery);

/**扩展datagrid编辑器，增加newradiobox、newcheckbox*/
(function($){
	$.extend($.fn.datagrid.defaults.editors, {
		newradiobox : {
			init : function(container, options) {
				var sel = $('<input/>').appendTo(container);
				sel.newradiobox(options);
				return sel;
			},
			destroy : function(target) {
				$(target).newradiobox('destroy');
			},
			getValue : function(target) {
				var value = $(target).newradiobox('getValue');
				return value;
			},
			setValue : function(target, value) {
				if (value) {
					$(target).newradiobox('setValue', value);
				}
			}
		}
	});
})(jQuery);

/** 扩展datagrid编辑器，增加combo多选支持 */
(function($) {
	$.extend($.fn.datagrid.defaults.editors, {
		newcheckbox : {
			init : function(container, options) {
				var sel = $('<input/>').appendTo(container);
				sel.newcheckbox(options);
				return sel;
			},
			getValue : function(target) {
				var values = $(target).newcheckbox('getValues');
				if ($.isArray(values)) {
					return values.join(",");
				} else {
					return values;
				}
			},
			setValue : function(target, value) {
				if (value) {
					var values = String(value).split(",");
					$(target).newcheckbox('setValues', values);
				} else {
					$(target).newcheckbox('setValues', []);
				}
			}
		}
	});
})(jQuery);

/** 扩展datagrid编辑器，增加imagebox支持 */
(function($) {
	$.extend($.fn.datagrid.defaults.editors, {
		ImageBox : {
			init : function(container, options) {
				/*var imageName = "__edite";
				var imgs = imageName + "Imgs";
				var src = imageName + "Src";
				var alter = imageName +"Alter";
				var upload = imageName + "Upload";
				var del = imageName + "Del";
				var img = "<div id='" + imgs + "' style='position:relative;padding-left:4px'>"
				+ "<img src='#' id='"+src+"' style='width:"+options.width+"px;height:"+options.height+"px;'/>"
				+ "<div id='" + alter + "' style='width:"+options.width+"px;height:16px;position:absolute;bottom:0px;background-color:#000;"
				+ "filter:alpha(opacity=50);-moz-opacity:0.5;-khtml-opacity:0.5;opacity:0.5' >"
				+ "<div title='上传图片' style='width:16px;height:16px;position:absolute;left:"+(options.width/2-22)+"px;'>"
				+ "<input type='file' name='uploadify_gs' id='" + upload + "' /></div>"
				+ "<div title='删除图片' style='width:16px;height:16px;position:absolute;left:"+(options.width/2+6)+"px;'>"
				+ "<input style='background-color:transparent;width:20px;height:20px;border:0px;outline:none;cursor:pointer' "
				+ "type='button' class='icon-remove' id='"+del+"' /></div>"
				+ "</div>"
				+ "<input __edite type='hidden' name='" + imageName + "' />";
				+ "</div>";
				container.append(img);
				uploadImage(upload, imageName, src, options.vPath);
				$("#" + imgs).dblclick(function(){
					   jQuery("#"+src).gzoomExpand($(this).find("img").attr("src"));
				});
				$("#" + del).click(function() {
					$("#"+src).attr("src", "#");
					$("#"+imgs+" input[__edite]").val("");
				});
				var target = container.children().data("vPath",options.vPath);
				return target;*/
				if(!options.onAfterSetImageBak) {
					options.onAfterSetImageBak = options.onAfterSetImage;
				}
				var func = options.onAfterSetImageBak;
				if(func) {
					options.onAfterSetImage = function(val) {
						var jq = $(this);
						var fieldKey = jq.closest('td.datagrid-cell-editing').attr('field');
						var rowIndex = jq.closest("tr.datagrid-row").attr("datagrid-row-index");
						var dg = jq.closest("div.datagrid-body").parent().nextAll("table");
						var rowData = dg.datagrid("getRows")[rowIndex];
						var tableKey = dg.attr("id");
						func(val, fieldKey, tableKey, rowIndex, rowData);
					};
				};
				return $('<input id="__editImage__">').appendTo(container).imagebox(options);
			},
			destroy : function(target) {
				target.remove();
			},
			getValue : function(target) {
				return target.imagebox("getValue");
			},
			setValue : function(target, value) {
				/*if (value) {
					$(target).find("input[__edite]").val(value);
					var src = $(target).data("vPath") + value;
					target.find("img").attr({src:src});
				}*/
				target.imagebox("setValue", value);
			},
			resize : function(target, width) {
				target.imagebox("resize", width);
			}
		}
	});
})(jQuery);

/** 扩展datagrid编辑器，增加dialoguewindow支持 */
(function($){
	$.extend($.fn.datagrid.defaults.editors, {
		dialoguewindow : {
			init : function(container, options) {
				return $('<input _isEditor="true" />').appendTo(container).dialoguewindow(options);
			},
			getValue : function(jq) {
				var val = jq.dialoguewindow("getValue");
				var field = jq.closest('td.datagrid-cell-editing').attr('field');
				var index = jq.closest("tr.datagrid-row").attr("datagrid-row-index");
				var row = jq.closest("div.datagrid-body").parent().nextAll("table").datagrid("getRows")[index];
				row[field+'text'] = val.caption;
				return val.key;
			},
			setValue : function(jq, value) {
				var field = jq.closest('td.datagrid-cell-editing').attr('field');
				var index = jq.closest("tr.datagrid-row").attr("datagrid-row-index");
				var row = jq.closest("div.datagrid-body").parent().nextAll("table").datagrid("getRows")[index];
				jq.dialoguewindow("setValue", {key: value, caption: row[field+'text']});
			},
			destroy : function(jq) {
				jq.dialoguewindow('destroy');
			},
			resize : function(jq, width) {
				jq.dialoguewindow('resize', width);
			}
		}
	});
})(jQuery);

/** 扩展datagrid编辑器，增加comboboxsearch支持 */
(function($){
	$.extend($.fn.datagrid.defaults.editors, {
		comboboxsearch : {
			init : function(target, opts) {
				return $("<input/>").appendTo(target).comboboxsearch(opts);
			},
			destroy : function(jq) {
				jq.comboboxsearch('destroy');
			},
			getValue : function(jq) {
				var opts = jq.comboboxsearch('options');
				return jq.comboboxsearch('getValues').join(opts.separator);
			},
			setValue : function(jq, value) {
				jq.comboboxsearch('setValues', value);
			},
			resize : function(jq, width) {
				jq.comboboxsearch('resize', width);
			}
		}
	});
})(jQuery);

/**
 * comboboxsearch - jQuery EasyUI 1.4.2
 * 
 * Dependencies:
 *   combobox
 *   
 * 控件带有继承关系，开发者需要注意与父控件顺序，一般子控件代码放在父控件之后
 * 项目中具体使用跟顺序没关系
 * 
 */
(function($){
	var COMBOBOX_SERNO = 0;
	
	/**
	 * scroll panel to display the specified item
	 */
	function scrollTo(target, value){
		var opts = $.data(target, 'combobox').options;
		var panel = $(target).combo('panel');
		var item = opts.finder.getEl(target, value);
		if (item.length){
			if (item.position().top <= 0){
				var h = panel.scrollTop() + item.position().top;
				panel.scrollTop(h);
			} else if (item.position().top + item.outerHeight() > panel.height()){
				var h = panel.scrollTop() + item.position().top + item.outerHeight() - panel.height();
				panel.scrollTop(h);
			}
		}
	}
	
	/**
	 * select the specified value
	 */
	function select(target, value, text){
		var state = $.data(target, 'combobox');
		state.texts = state.texts || [];
		var opts = state.options;
		var values = $(target).combo('getValues');
		if ($.inArray(value+'', values) == -1){
			if (opts.multiple){
				values.push(value);
				state.texts.push(text);
			} else {
				values = [value];
			}
			setValues(target, values);
			opts.onSelect.call(target, opts.finder.getRow(target, value));
		}
	}
	
	/**
	 * unselect the specified value
	 */
	function unselect(target, value, text){
		var state = $.data(target, 'combobox');
		state.texts = state.texts || [];
		var opts = state.options;
		var values = $(target).combo('getValues');
		var index = $.inArray(value+'', values);
		if (index >= 0){
			values.splice(index, 1);
			state.texts.splice(index, 1);
			setValues(target, values);
			opts.onUnselect.call(target, opts.finder.getRow(target, value));
		}
	}
	
	/**
	 * set values
	 */
	function setValues(target, values, remainText){
		var state = $.data(target, 'combobox');
		state.texts = state.texts || [];
		var opts = state.options;
		var panel = $(target).combo('panel');
		
		/*拆分多选 start*/
		if (!$.isArray(values)){values = (values ? String(values).split(opts.separator) : []);}
		/*拆分多选 end*/
		panel.find('div.combobox-item-selected').removeClass('combobox-item-selected');
		var vv = [], ss = [];
		for(var i=0; i<values.length; i++){
			var v = values[i];
			var s = v;
			opts.finder.getEl(target, v).addClass('combobox-item-selected');
			var row = opts.finder.getRow(target, v);
			if (row){
				s = row[opts.textField];
			}
			vv.push(v);
			ss.push(s);
		}
		ss = (vv.length && state.texts.length)?state.texts:ss;
		state.texts = ss;
		if (!remainText){
			$(target).combo('setText', ss.join(opts.separator));
		}
		$(target).combo('setValues', vv);
	}
	
	/**
	 * load data, the old list items will be removed.
	 */
	function loadData(target, data, remainText){
		var state = $.data(target, 'combobox');
		var opts = state.options;
		state.data = opts.loadFilter.call(target, data);
		state.groups = [];
		data = state.data;
		
		var selected = $(target).combobox('getValues');
		var comboPanel = $(target).combo('panel');
		var isNeedInitChaXun = (comboPanel.find("input._chaxun").length == 0);//是否需要初始化查询框
		var dd = [];
		if(isNeedInitChaXun) {
			/*查询框 start*/
			dd.push("<input type='text' class='_chaxun' placeholder='输入关键字查询' style='padding:0 4px;border-width:0px 0px 1px 0px;height:20px;width:");
			dd.push(opts.width-2);
			dd.push("px'/>");
			dd.push('<div class="_clear_" style="text-align:center;color:gray;cursor:pointer;"><span>x</span><span>清空选中数据</span></div>');
			//dd.push("<div style='overflow:auto;'>");
			/*查询框 end*/
		}
		var group = undefined;
		for(var i=0; i<data.length; i++){
			var row = data[i];
			var v = row[opts.valueField]+'';
			var s = row[opts.textField];
			var g = row[opts.groupField];
			
			if (g){
				if (group != g){
					group = g;
					state.groups.push(g);
					dd.push('<div id="' + (state.groupIdPrefix+'_'+(state.groups.length-1)) + '" class="combobox-group">');
					dd.push(opts.groupFormatter ? opts.groupFormatter.call(target, g) : g);
					dd.push('</div>');
				}
			} else {
				group = undefined;
			}
			
			var cls = 'combobox-item' + (row.disabled ? ' combobox-item-disabled' : '') + (g ? ' combobox-gitem' : '');
			dd.push('<div id="' + (state.itemIdPrefix+'_'+i) + '" class="' + cls + '">');
			dd.push(opts.formatter ? opts.formatter.call(target, row) : s);
			dd.push('</div>');
			
			if (row['selected'] && $.inArray(v, selected) == -1){
				selected.push(v);
			}
		}
		//dd.push("</div>");
		if(isNeedInitChaXun) {
			comboPanel.html(dd.join(''))
			.find("input._chaxun").unbind()
			.bind('keydown', function(e) {
				/*因为查询框在datagrid之外，键盘事件无法通过冒泡传递到*/
				/*防止此处代码逻辑过于复杂，回调input元素绑定事件处理函数*/
				e.target = $(target).next().find('input:visible')[0];
				switch (e.keyCode) {
				case 38:
				case 40:
					$(target).next().find('input:visible').trigger(e);
					break;
				case 13:
					$(target).next().find('input:visible').trigger(e);
					e.preventDefault();/* 阻止enter默认事件 */
					break;
				case 9:
				case 27:
					$(target).next().find('input:visible').focus()/*更改焦点位置*/.trigger(e);
					e.preventDefault();/* 阻止enter默认事件 */
					break;
				case 37:
				case 39:
					if(!$(this).val()) $(target).next().find('input:visible').trigger(e);
					break;
				}
				e.stopPropagation();
			})
			.bind('keyup', function(e) {
				switch (e.keyCode) {
				case 9:
				case 13:
				case 27:
				case 37:
				case 38:
				case 39:
				case 40:
					break;
				default:
					if(state.queryTimer){
						clearTimeout(state.queryTimer);
					}
					var q = $(this).val();
					state.queryTimer = setTimeout(function(){
						doQuery(target, q);	
					}, opts.queryDelay);
				}
				e.stopPropagation();
			});
			//清除选中数据
			$(target).combo('panel').find("div._clear_").click(function() {
				setValues(target, []);
				$(this).prev().val("").focus();
			});
			/*查询框end*/
		} else {//搜索时使用
			comboPanel.find("div.combobox-item").remove();
			comboPanel.append(dd.join(''));
		}
		if (opts.multiple){
			setValues(target, selected, remainText);
		} else {
			setValues(target, selected.length ? [selected[selected.length-1]] : [], remainText);
		}
		
		opts.onLoadSuccess.call(target, data);
	}
	
	/**
	 * request remote data if the url property is setted.
	 */
	function request(target, url, param, remainText){
		var opts = $.data(target, 'combobox').options;
		if (url){
			opts.url = url;
		}
		param = $.extend({}, opts.queryParams, param||{});
		/*if(opts["onSetQueryParam"]) {
			param = $.extend(true, {}, param, opts["onSetQueryParam"].call(target, param, opts["rowData"], opts["rowIndex"]));
		}*/
		
		if (opts.onBeforeLoad.call(target, param) == false) return;

		opts.loader.call(target, param, function(data){
			loadData(target, data, remainText);
		}, function(){
			opts.onLoadError.apply(this, arguments);
		});
	}
	
	
	/**
	 * do the query action
	 */
	function doQuery(target, q){
		var state = $.data(target, 'combobox');
		var opts = state.options;
		
		var qq = opts.multiple ? q.split(opts.separator) : [q];
		if (opts.mode == 'remote'){
			/*载入数据列表方式，远程数据*/
			request(target, null, {q:q}, true);
		} else {
			var panel = $(target).combo('panel');
			//panel.find('div.combobox-item-selected,div.combobox-item-hover').removeClass('combobox-item-selected combobox-item-hover');
			panel.find('div.combobox-item,div.combobox-group').hide();
			var data = state.data;
			$.map(qq, function(q){
				q = $.trim(q);
				var group = undefined;
				for(var i=0; i<data.length; i++){
					var row = data[i];
					if (opts.filter.call(target, q, row)){
						var v = row[opts.valueField];
						var s = row[opts.textField];
						var g = row[opts.groupField];
						opts.finder.getEl(target, v).show();
						if (s.toLowerCase() == q.toLowerCase()){
							select(target, v);
						}
						if (opts.groupField && group != g){
							$('#'+state.groupIdPrefix+'_'+$.inArray(g, state.groups)).show();
							group = g;
						}
					}
				}
			});
		}
	}
	
	/**
	 * create the component
	 */
	function create(target, isFirst){
		var state = $.data(target, 'combobox');
		var opts = state.options;
		
		if(isFirst) {
			COMBOBOX_SERNO++;
			/*避免与combobox重复，必须改为_easyui_comboboxsearch_*/
			state.itemIdPrefix = '_easyui_comboboxsearch_i' + COMBOBOX_SERNO;
			state.groupIdPrefix = '_easyui_comboboxsearch_g' + COMBOBOX_SERNO;
			
			$(target).addClass('combobox-f');
			var oldOnShowPanel = opts.onShowPanel;
			var onShowPanel = function() {
				scrollTo(target, $(target).combobox('getValue'));
				oldOnShowPanel && oldOnShowPanel.call(target);
				/*打开comboboxsearch面板时，使焦点落在查询框中
				 *对非远程加载的comboboxsearch，200ms足够执行完$(_917).combo("textbox").focus();
				 *若需要100%保证焦点落在查询框中，可覆盖combo的inputEvents*/
				if (state.focusTimer) {
					clearTimeout(state.focusTimer);
				}
				state.focusTimer = setTimeout(function() {
					$(target).combo('panel').find('input._chaxun').focus();/*设置焦点到查询框*/
				}, opts.focusDelay);
			};
			opts.onShowPanel = onShowPanel;
		}
		
		$(target).combo(opts);
		
		if(isFirst) {
			$(target).combo('panel').unbind().bind('mouseover', function(e){
				$(this).children('div.combobox-item-hover').removeClass('combobox-item-hover');
				var item = $(e.target).closest('div.combobox-item');
				if (!item.hasClass('combobox-item-disabled')){
					item.addClass('combobox-item-hover');
				}
				e.stopPropagation();
			}).bind('mouseout', function(e){
				$(e.target).closest('div.combobox-item').removeClass('combobox-item-hover');
				e.stopPropagation();
			}).bind('click', function(e){
				var item = $(e.target).closest('div.combobox-item');
				if (!item.length || item.hasClass('combobox-item-disabled')){return;}
				var row = opts.finder.getRow(target, item);
				if (!row){return;}
				var value = row[opts.valueField];
				var text = row[opts.textField];
				if (opts.multiple){
					if (item.hasClass('combobox-item-selected')){
						unselect(target, value, text);
					} else {
						select(target, value, text);
					}
				} else {
					select(target, value, text);
					$(target).combo('hidePanel');
				}
				e.stopPropagation();
			});
		}
	}
	
	$.fn.comboboxsearch = function(options, param){
		if (typeof options == 'string'){
			var method = $.fn.comboboxsearch.methods[options];
			if (method){
				return method(this, param);
			} else {
				return this.combobox(options, param);
			}
		}
		
		options = options || {};
		return this.each(function(){
			var state = $.data(this, 'combobox');
			if (state){
				$.extend(true, state.options, options);
				//$(this).combo(state.options);
				create(this, false);
			} else {
				state = $.data(this, 'combobox', {
					options: $.extend({}, $.fn.comboboxsearch.defaults, $.fn.combobox.parseOptions(this), options),
					data: []
				});
				create(this, true);
				var data = $.fn.combobox.parseData(this);
				if (data.length){
					loadData(this, data);
				}
			}
			if (state.options.data){
				loadData(this, state.options.data);
			}
			request(this);
		});
	};
	
	$.fn.comboboxsearch.defaults = $.extend({}, $.fn.combobox.defaults, {
		editable : false,
		queryDelay: 200,
		focusDelay: 200
	});
	
	$.fn.comboboxsearch.methods = {
		loadData: function(jq, data){
			return jq.each(function(){
				loadData(this, data);
			});
		},
		resize: function(jq, width){
			jq.combo("panel").find("input._chaxun").width(width-2);
			return jq.combo("resize", width);
		}
	};
})(jQuery);

/**
 * 扩展comboboxsearch编辑器，增加ComboCheck支持
 */
(function($) {
	
	$.fn.combocheck = function(options, param) {// 初始化方法
		if (typeof options == 'string') {
			return this.comboboxsearch(options, param);
		}
		options = options || {};
		options.multiple = true;
		return this.each(function() {
			var state = $.data(this, "combocheck");
			if (state) {
				$.extend(state.options, options);
			} else {
				state = {
					options : $.extend({}, $.fn.combocheck.defaults, options)
				};
				$.data(this, "combocheck", state);
				$(this).comboboxsearch($.extend({}, state.options, {
					onSelect : function(record){
						var opts = state.options;
						opts.finder.getEl(this, record[opts.valueField]).children(
							'input:checkbox').prop("checked", true);
						opts.onSelect.call(this, record);
					},
					onUnselect : function(record){
						var opts = state.options;
						opts.finder.getEl(this, record[opts.valueField]).children(
							'input:checkbox').prop("checked", false);
						opts.onUnselect.call(this, record);
					},
					onShowPanel : function(){
						$(this).combocheck('panel')
						.find('div.combobox-item').each(function(){
							if($(this).is('.combobox-item-selected')){
								$(this).children('input:checkbox').prop("checked", true);
							}else{
								$(this).children('input:checkbox').prop("checked", false);
							}
						});
						//设置texts属性
						var opts = $.data(this, 'combobox');
						var text = $(this).combobox("getText");
						if(text) {
							opts.texts = text.split(",");
						}
						state.options.onShowPanel.call(this);
					}
				})).combocheck('panel')
				.find('div.combobox-item')
				.prepend('<input type="checkbox"/>');
			}
		});
	};

	$.fn.combocheck.defaults = $.extend({}, $.fn.comboboxsearch.defaults, {// 属性和事件
		multiple : true,
		valueField : "key",
		textField : "caption",
		mode : "local",
		method : "post"
	});
	
})(jQuery);

/**
 * tabs - jQuery EasyUI
 * 
 * Dependencies:
 * 	 panel
 *   linkbutton
 * 
 */
(function($) {
	/**
	 * update tab panel, param has following properties: tab: the tab panel to
	 * be updated options: the tab panel options type: the update type, possible
	 * values are: 'header','body','all'
	 */
	function updateTab(container, param) {
		param.type = param.type || 'all';
		var selectHis = $.data(container, 'tabs').selectHis;
		var pp = param.tab; // the tab panel
		/*获取修改前的title*/
		var oldTitle = pp.panel('options').tab.find('span.tabs-title').html();

		if (param.type == 'all' || param == 'body') {
			pp.panel($.extend({}, param.options, {
				iconCls : (param.options.icon ? param.options.icon : undefined)
			}));
		}
		if (param.type == 'all' || param.type == 'header') {
			var opts = pp.panel('options'); // get the tab panel options
			var tab = opts.tab;

			if (opts.header) {
				tab.find('.tabs-inner').html($(opts.header));
			} else {
				var s_title = tab.find('span.tabs-title');
				var s_icon = tab.find('span.tabs-icon');
				s_title.html(opts.title);
				s_icon.attr('class', 'tabs-icon');

				tab.find('a.tabs-close').remove();
				if (opts.closable) {
					s_title.addClass('tabs-closable');
					$('<a href="javascript:void(0)" class="tabs-close"></a>')
							.appendTo(tab);
				} else {
					s_title.removeClass('tabs-closable');
				}
				if (opts.iconCls) {
					s_title.addClass('tabs-with-icon');
					s_icon.addClass(opts.iconCls);
				} else {
					s_title.removeClass('tabs-with-icon');
				}
				if (opts.tools) {
					var p_tool = tab.find('span.tabs-p-tool');
					if (!p_tool.length) {
						var p_tool = $('<span class="tabs-p-tool"></span>')
								.insertAfter(tab.find('a.tabs-inner'));
					}
					if ($.isArray(opts.tools)) {
						for ( var i = 0; i < opts.tools.length; i++) {
							var t = $('<a href="javascript:void(0)"></a>')
									.appendTo(p_tool);
							t.addClass(opts.tools[i].iconCls);
							if (opts.tools[i].handler) {
								t.bind('click', {
									handler : opts.tools[i].handler
								}, function(e) {
									if ($(this).parents('li').hasClass(
											'tabs-disabled')) {
										return;
									}
									e.data.handler.call(this);
								});
							}
						}
					} else {
						$(opts.tools).children().appendTo(p_tool);
					}
					var pr = p_tool.children().length * 12;
					if (opts.closable) {
						pr += 8;
					} else {
						pr -= 3;
						p_tool.css('right', '5px');
					}
					s_title.css('padding-right', pr + 'px');
				} else {
					tab.find('span.tabs-p-tool').remove();
					s_title.css('padding-right', '');
				}
			}
			if (oldTitle != opts.title) {
				for ( var i = 0; i < selectHis.length; i++) {
					if (selectHis[i] == oldTitle) {
						selectHis[i] = opts.title;
					}
				}
			}
		}
		
		$(container).tabs('resize');

		$.data(container, 'tabs').options.onUpdate.call(container, opts.title, getTabIndex(container, pp));
	}
	
	function createTab(container, options, pp) {
		options = options || {};
		var state = $.data(container, 'tabs');
		var tabs = state.tabs;
		if (options.index == undefined || options.index > tabs.length){options.index = tabs.length}
		if (options.index < 0){options.index = 0}
		
		var ul = $(container).children('div.tabs-header').find('ul.tabs');
		var panels = $(container).children('div.tabs-panels');
		var tab = $(
				'<li>' +
				'<a href="javascript:void(0)" class="tabs-inner">' +
				'<span class="tabs-title"></span>' +
				'<span class="tabs-icon"></span>' +
				'</a>' +
				'</li>');
		if (!pp){pp = $('<div></div>');}
		if (options.index >= tabs.length){
			tab.appendTo(ul);
			pp.appendTo(panels);
			tabs.push(pp);
		} else {
			tab.insertBefore(ul.children('li:eq('+options.index+')'));
			pp.insertBefore(panels.children('div.panel:eq('+options.index+')'));
			tabs.splice(options.index, 0, pp);
		}
		
		/* onDblClick事件的支持在1.4版easyui被取消 */
		/*双击标题事件，对通过add添加的面板标题有效*/
		tab.bind('dblclick', function(e) {
			var title = $(this).find('span.tabs-title').html();
			state.options.onDblClick.call(this, e, title);
		});
		
		// create panel
		pp.panel($.extend({}, options, {
			tab: tab,
			border: false,
			noheader: true,
			closed: true,
			doSize: false,
			iconCls: (options.icon ? options.icon : undefined),
			onLoad: function(){
				if (options.onLoad){
					options.onLoad.call(this, arguments);
				}
				state.options.onLoad.call(container, $(this));
			},
			onBeforeOpen: function(){
				if (options.onBeforeOpen){
					if (options.onBeforeOpen.call(this) == false){return false;}
				}
				var p = $(container).tabs('getSelected');
				if (p){
					if (p[0] != this){
						$(container).tabs('unselect', getTabIndex(container, p));
						p = $(container).tabs('getSelected');
						if (p){
							return false;
						}
					} else {
						setSelectedSize(container);
						return false;
					}
				}
				
				var popts = $(this).panel('options');
				popts.tab.addClass('tabs-selected');
				// scroll the tab to center position if required.
				var wrap = $(container).find('>div.tabs-header>div.tabs-wrap');
				var left = popts.tab.position().left;
				var right = left + popts.tab.outerWidth();
				if (left < 0 || right > wrap.width()){
					var deltaX = left - (wrap.width()-popts.tab.width()) / 2;
					$(container).tabs('scrollBy', deltaX);
				} else {
					$(container).tabs('scrollBy', 0);
				}
				
				var panel = $(this).panel('panel');
				panel.css('display','block');
				setSelectedSize(container);
				panel.css('display','none');
			},
			onOpen: function(){
				if (options.onOpen){
					options.onOpen.call(this);
				}
				var popts = $(this).panel('options');
				state.selectHis.push(popts.title);
				state.options.onSelect.call(container, popts.title, getTabIndex(container, this));
			},
			onBeforeClose: function(){
				if (options.onBeforeClose){
					if (options.onBeforeClose.call(this) == false){return false;}
				}
				$(this).panel('options').tab.removeClass('tabs-selected');
			},
			onClose: function(){
				if (options.onClose){
					options.onClose.call(this);
				}
				var popts = $(this).panel('options');
				state.options.onUnselect.call(container, popts.title, getTabIndex(container, this));
			}
		}));
		
		// only update the tab header
		$(container).tabs('update', {
			tab: pp,
			options: pp.panel('options'),
			type: 'header'
		});
	}
	
	function addTab(container, options) {
		var state = $.data(container, 'tabs');
		var opts = state.options;
		if (options.selected == undefined) {
			options.selected = true;
		}
		createTab(container, options);
		opts.onAdd.call(container, options.title, options.index);
		
		if (options.selected) {
			$(container).tabs("select", options.index); // select the added tab panel
		}
	}

	/**
	 * set selected tab panel size
	 */
	function setSelectedSize(container) {
		var opts = $.data(container, 'tabs').options;
		var tab = getSelectedTab(container);
		if (tab) {
			var panels = $(container).children('div.tabs-panels');
			var width = opts.width == 'auto' ? 'auto' : panels.width();
			var height = opts.height == 'auto' ? 'auto' : panels.height();
			tab.panel('resize', {
				width : width,
				height : height
			});
		}
	}

	function getSelectedTab(container) {
		var tabs = $.data(container, 'tabs').tabs;
		for ( var i = 0; i < tabs.length; i++) {
			var tab = tabs[i];
			if (tab.panel('options').tab.hasClass('tabs-selected')) {
				return tab;
			}
		}
		return null;
	}
	
	function getTabIndex(container, tab) {
		var tabs = $.data(container, 'tabs').tabs;
		for ( var i = 0; i < tabs.length; i++) {
			if (tabs[i][0] == $(tab)[0]) {
				return i;
			}
		}
		return -1;
	}
	
	$.extend($.fn.tabs.methods, {
		update : function(jq, options) {
			return jq.each(function() {
				updateTab(this, options);
			});
		},
		add : function(jq, options){
			return jq.each(function(){
				addTab(this, options);
			});
		}
	});
	
	$.fn.tabs.defaults.onDblClick = function(e, title) { };
	
})(jQuery);

/**
 * form - jQuery EasyUI
 * 
 */
(function($){
	/**
	 * load form data
	 * if data is a URL string type load from remote site, 
	 * otherwise load from local data object. 
	 */
	
	/*添加'comboboxsearch','newradiobox','newcheckbox','combo'以控件方式load数据*/
	$.fn.form.defaults = $.extend({}, $.fn.form.defaults, {
		fieldTypes: ['comboboxsearch','combobox','combotree','combogrid','datetimebox','datebox','combocheck','comboradio',
		             	'newradiobox','newcheckbox','combo',
				        'datetimespinner','timespinner','numberspinner','spinner',
				        'slider','searchbox','numberbox','textbox','comboboxsearch','dialoguewindow']
	});
	

	function load(_4dc, data) {
		var opts = $.data(_4dc, "form").options;
		if (typeof data == "string") {
			var _4dd = {};
			if (opts.onBeforeLoad.call(_4dc, _4dd) == false) {
				return;
			}
			$.ajax({
				url : data,
				data : _4dd,
				dataType : "json",
				success : function(data) {
					_4de(data);
				},
				error : function() {
					opts.onLoadError.apply(_4dc, arguments);
				}
			});
		} else {
			_4de(data);
		}
		function _4de(data) {
			var form = $(_4dc);
			for ( var name in data) {
				var val = data[name];
				if (!_4e0(name, val)) {
					if (!_4df(name, val)) {
						form.find("input[name=\"" + name + "\"]:not(.combotree)").val(val);
						//combotree组件加载数据
						form.find("input[name=\"" + name + "\"].combotree").each(function() {
							$ES.setSelectTreeValText(this, val, data[name+"_caption"]);
						});
						form.find("textarea[name=\"" + name + "\"]").val(val);
						//form.find("select[name=\"" + name + "\"]").val(val);
						//combobox组件加载数据
						form.find("select[name=\"" + name + "\"]:not(.combobox)").val(val);
						form.find("select[name=\"" + name + "\"].combobox").each(function() {
							$(this).data("notTriggerChange", true);
							$ES.setComboBoxValText(this, val, data[name+"_caption"]);
						});
					}
				}
			}
			opts.onLoadSuccess.call(_4dc, data);
			//form.form("validate");
		};
		function _4df(name, val) {
			var cc = $(_4dc).find(
					"input[name=\"" + name + "\"]:radio, input[name=\""
							+ name + "\"]:checkbox");
			if (cc.length) {
				cc._propAttr("checked", false);
				cc.each(function() {
					var f = $(this);
					if (f.val() == String(val)
							|| $.inArray(f.val(), $.isArray(val) ? val
									: [ val ]) >= 0) {
						f._propAttr("checked", true);
					}
				});
				return true;
			}
			return false;
		};
		function _4e0(name, val) {
			var _4e1 = $(_4dc).find(
					"[textboxName=\"" + name + "\"],[sliderName=\"" + name
							+ "\"]");
			if (_4e1.length) {
				for ( var i = 0; i < opts.fieldTypes.length; i++) {
					var type = opts.fieldTypes[i];
					var _4e2 = _4e1.data(type);
					if (_4e2) {
						var onChangeEvent = _4e2.options.onChange;//加载数据时，不触发事件
						_4e2.options.onChange = function() {};
						//取消combo-onChange事件
						var combo = _4e1.data("combo");
						var comboOnChangeEvent = null;
						if(combo) {
							comboOnChangeEvent = combo.options.onChange;
							combo.options.onChange = function() {};
						}
						//取消textbox-onChange事件
						var textbox = _4e1.data("textbox");
						var textboxOnChangeEvent = null;
						if(textbox) {
							textboxOnChangeEvent = textbox.options.onChange;
							textbox.options.onChange = function() {};
						}
						
						if (_4e2.options.multiple || _4e2.options.range) {
							_4e1[type]("setValues", val);
							if(type=="combobox" && _4e2.options.url) {
								var val = _4e1.combobox("getValues");
								var txt = _4e1.combobox("getText");
								if(val.join(",") == txt) _4e1.combobox("reload");
							}
						} else {
							_4e1[type]("setValue", val);
							if(type=="combobox" && _4e2.options.url) {
								var val = _4e1.combobox("getValue");
								var txt = _4e1.combobox("getText");
								if(val == txt) _4e1.combobox("reload");
							}
						}
						
						if(textbox) {
							textbox.options.onChange = textboxOnChangeEvent;
						}
						if(combo) {
							combo.options.onChange = comboOnChangeEvent;
						}
						_4e2.options.onChange = onChangeEvent;
						return true;
					}
				}
			}
			return false;
		};
	};
	//重写form load方法
	$.fn.form.methods = $.extend({}, $.fn.form.methods, {
		load : function(jq, data) {
			return jq.each(function(){
				load(this,data);
			});
		}
	});
	
})(jQuery);

/**
 * combotree - jQuery EasyUI
 * 
 */
(function($){
	
	function setValues(target, values) {
		var state = $.data(target, "combotree");
		var opts = state.options;
		var tree = state.tree;
		var treeOptions = tree.tree("options");
		var onCheck = treeOptions.onCheck;
		var onSelect = treeOptions.onSelect;
		treeOptions.onCheck = treeOptions.onSelect = function() {
		};
		tree.find("span.tree-checkbox").addClass("tree-checkbox0").removeClass(
				"tree-checkbox1 tree-checkbox2");
		if (!$.isArray(values)) {
			/* 修复combotree回显空值报错 start */
			values = values ? String(values).split(opts.separator) : [];
			/* 修复combotree回显空值报错 end */
		}
		var vv = $.map(values, function(value) {
			if(value===undefined || value===null) return "";
			else return String(value);
		});
		var ss = [];
		$.map(vv, function(v) {
			var node = tree.tree("find", v);
			if (node) {
				tree.tree("check", node.target).tree("select", node.target);
				ss.push(node.text);
			} else {
				ss.push(v);
			}
		});
		if (opts.multiple) {
			var nodes = tree.tree("getChecked");
			$.map(nodes, function(node) {
				var id = String(node.id);
				if ($.inArray(id, vv) == -1) {
					vv.push(id);
					ss.push(node.text);
				}
			});
		}
		treeOptions.onCheck = onCheck;
		treeOptions.onSelect = onSelect;
		$(target).combo("setText", ss.join(opts.separator)).combo("setValues",
				opts.multiple ? vv : (vv.length ? vv : [ "" ]));
	};
	
	$.fn.combotree.methods = $.extend({}, $.fn.combotree.methods, {
		setValues : function(jq, values) {
			return jq.each(function() {
				setValues(this, values);
			});
		},
		setValue : function(jq, value) {
			return jq.each(function() {
				setValues(this, [value]);
			});
		}
	});
})(jQuery);

var $MsgUtil = {
	alert:function(msg) {
		$.messager.alert("提示",msg,"info");
	}	
};

/**
基于zTree扩展，树形组件支持
2016-03-31 gxj
**/
(function($) {
	
	var _doCheckNodesOnTree_ = function(treeId, param) {
		if(!param) {
			$MsgUtil.alert("请输入匹配关键字");
			return;
		}
		var treeObj = $.fn.zTree.getZTreeObj(treeId);
		var nodes = treeObj.getNodesByParamFuzzy("name", param, null);
		/*for (var i=0, l=nodes.length; i < l; i++) {
			treeObj.selectNode(nodes[i]);
		}*/
		if(nodes.length) treeObj.selectNode(nodes[0]);
	}
	
	var init = function(jq, opt) {
		var treeHtml = '<div style="padding:6px 10px;">' 
					 + '<input id="_query_tree_q_" type="text" class="form-control" placeholder="请输入关键字查询" style="width:400px;"/>'
					 + '</div>'
					 + '<ul class="ztree" id="_esTree_" style="width:420px;border:0;background-color:#fff;overflow-y:auto;"></ul>';
		$(jq).html(treeHtml);
		
		$("#_query_tree_q_").textbox({
			prompt:"请输入关键字查询",
			icons : [ {
				iconCls : 'searchbox-button',
				handler : function(e) {
					_doCheckNodesOnTree_('_esTree_', $('#_query_tree_q_').textbox("getValue"));
				}
			}]
		});
		
		$($("#_query_tree_q_").textbox("textbox")).bind("keydown", "return", function(evt) {
			_doCheckNodesOnTree_('_esTree_', $(this).val());
			return false;
		});
		
		var treeSetting = {
			data : {
				key : {
					name : "name"
				},
				simpleData : {
					enable : true,
					idKey : "id",
					pIdKey : opt["pIdKey"]
				}
			},
			callback : {
				onClick:opt["onclick"],
				onDblClick:opt["onDblClick"],
				onCheck:opt["onCheck"],
				onCollapse:opt["onCollapse"],
				onExpand:opt["onExpand"]
			}
		};
		if(opt["multiple"]) {
			treeSetting["check"] = $.extend(true, {}, {
				enable : true,
				chkboxType: { "Y": "s", "N": "s" }
			}, opt["checkOpt"]);
		}
		var ajaxOpt = {
			url : opt["url"],
			data : opt["queryParams"],
			async : true,
			success : function(data) {
				var result = $.isArray(data) ? data : data.msg;
				if (result) {
					$.fn.zTree.init($("#_esTree_"), treeSetting, result);
					if(opt["value"]) {//默认选中值
						$.fn.esTree.methods["setValue"]($(jq), opt["value"]);
					}
				}
			}
		};
		fnFormAjaxWithJson(ajaxOpt);
	}
	
	$.fn.esTree = function(options, param) {		
		if(typeof options == 'string'){
			var opt=$.fn.esTree.methods[options];
			if(opt){
				return opt(this, param);
			}
		}
        return this.each(function() {
        	var state = $(this).data("option");
			if (state) {
				$.extend(state, options);
			} else {
				state = $.extend({}, $.fn.esTree.defaults,options);
				$(this).data("option", state);
				init(this, state);
			}           
        });
   };
	
	$.fn.esTree.defaults = {
		url:"",
		queryParams:"",
		multiple:false,
		pIdKey:"pid",
		idValPrefix:"",//id值前缀
		valMap:{"idKey":"id","textKey":"name"},//取值字段映射
		checkOpt:{} //树check opt
	};
	
	$.fn.esTree.methods = {
		options:function(jq, param) {
			return jq.data("option");
		},
		getValue: function(jq){
			var opt = $.fn.esTree.methods["options"](jq);
			var treeObj =  $.fn.zTree.getZTreeObj("_esTree_");
			var nodes = (opt["multiple"]) ? treeObj.getCheckedNodes() : treeObj.getSelectedNodes();
			return nodes;
		},
		getResult: function(jq){
			var nodes = $.fn.esTree.methods["getValue"](jq);
			var idArr = [],textArr = [];
			if(nodes && nodes.length) {
				var opt = $.fn.esTree.methods["options"](jq);
				var valMap = opt["valMap"];
				var idValPrefix = opt["idValPrefix"];
				for(var i in nodes) {
					var tmpObj = nodes[i];
					var idVal = tmpObj[valMap["idKey"]];
					if(idValPrefix) {
						if(idVal.indexOf(idValPrefix) == 0) {
							idArr.push(idVal.slice(idValPrefix.length));
							textArr.push(tmpObj[valMap["textKey"]]);
						}
					} else {
						idArr.push(idVal);
						textArr.push(tmpObj[valMap["textKey"]]);
					}
				}
			}
			return {id:idArr.join(","), text:textArr.join(",")};
		},
		setValue: function(jq, value){
			var treeObj =  $.fn.zTree.getZTreeObj("_esTree_");
			var opt = $.fn.esTree.methods["options"](jq);
			var idValPrefix = opt["idValPrefix"];
			if(opt["multiple"]) {
				treeObj.checkAllNodes(false);
			} else {
				treeObj.cancelSelectedNode();
			}
			value = String(value);
			if(value) {
				var valArr = value.split(",");
				if(valArr && valArr.length) {
					var valMap = opt["valMap"];
					for(var i in valArr) {
						var node = treeObj.getNodeByParam(valMap["idKey"], idValPrefix + valArr[i], null);
						if(node) {
							if(opt["multiple"]) {
								treeObj.checkNode(node, true, true);
							} else {
								treeObj.selectNode(node, true);
							}
						}
					}
				}
			}
		},
		enable : function(jq){
			return jq.each(function() {
				
			});
		},
		disable : function(jq){
			return jq.each(function() {
				
			});
		},
		destroy: function(jq){
			var treeObj =  $.fn.zTree.getZTreeObj("_esTree_");
			treeObj.destroy();
		}
	};
	
})(jQuery);

/*
2016-04-01 表单弹出树组件
*/
(function($) {
   
	var init = function(jq) {
		var $wrap = $(jq),
			$prepend = $('<div class="input-group">' 
					 + '<input type="text" class="form-control read-only" placeholder="请选择"/>'
					 + '</div>'),
			$wrapInput = $prepend.find("input"),
			$wrapBt = $prepend.find("button");
		$wrapInput.width($wrap.width());
		$wrap.addClass("hidden").hide();
		$prepend.insertBefore($wrap);
		
		var opt = $wrap.data("option");
		opt["onAfterSure"] = function(result) {
			var oldValue = $wrap.val();
			$wrap.val(result.id);
			$wrapInput.textbox("setValue",result.text);
			if(opt.onChange) {
				var newValue = result.id;
				if(oldValue != newValue) {
					opt.onChange.call($wrap, newValue, oldValue);
				}
			}
			return true;
		}
		
		$wrapInput.textbox({
			icons : [ {
				iconCls : 'dialogue-window',
				handler : function(e) {
					var opt = $wrap.data("option");
					opt["value"] = $wrap.val();//默认值
					showTree(opt);
				}
			}]
		});
	};
	//初始化bootstrap风格
	var initBootstrap = function(jq) {
		var $wrap = $(jq),
		$prepend = $('<div class="input-group input-group-sm">' 
				 + '<input type="text" class="form-control read-only" placeholder="请选择" readonly="true"/>'
				 + '<span class="input-group-btn">'
				 + '<a class="btn btn-default" type="button">'
				 + '<span class="glyphicon glyphicon-list"></span>'
				 + '</a></span></div>'),
			$wrapInput = $prepend.find("input"),
			$wrapBt = $prepend.find("a.btn");
		if(!$wrap.attr("notAutoWidth")) $wrapInput.width($wrap.width());
		$wrapInput.attr("required", $wrap.attr("required"));
		$wrap.addClass("hidden").hide();
		$prepend.insertBefore($wrap);
		
		var opt = $wrap.data("option");
		opt["onAfterSure"] = function(result) {
			var oldValue = $wrap.val();
			$wrap.val(result.id);
			$wrapInput.val(result.text);
			if(opt.onChange) {
				var newValue = result.id;
				if(oldValue != newValue) {
					opt.onChange.call($wrap, newValue, oldValue);
				}
			}
			return true;
		}
		
		$wrapBt.off("click").on("click", function(event) {
			opt["value"] = $wrap.val();//默认值
			showTree(opt);
		});
	};
	
	var showTree = function(opt) {
		var win = "<div id='_form_select_tree_' style='width:100%;height:100%'></div>";	
		var p =	$("<div/>").appendTo("body");
		p.dialog({
			id:'_select_tree_dialog_',
			title:'请选择',
			content:win,
			width:500,
			height:480,
			closable:true,
			collapsible:true,
			maximizable:true,
			minimizable:false,
			resizable:true,
			modal: true,
			shadow: false,
			cache:false,
			closed:true,
			onOpen:function() {
				var esTreeOpt = $.extend(true, {}, opt);
				delete esTreeOpt["onAfterSure"];
				$("#_form_select_tree_").esTree(esTreeOpt);
			},
			onClose:function() {
				$("#_select_tree_dialog_").dialog("destroy");
			},
			buttons:[{
				text:'确定',
				iconCls:'icon-ok',
				handler:function(){
					if(opt["onAfterSure"]) {
						var result = $("#_form_select_tree_").esTree("getResult");
						if(opt["onAfterSure"](result)) {
							$('#_select_tree_dialog_').dialog('close');
						}
					}
					return false;
				}
			},{
				text:'取消',
				iconCls:'icon-cancel',
				handler:function(){
					$('#_select_tree_dialog_').dialog('close');
				}
			}]
		});
		$("#_select_tree_dialog_").dialog("open");
		
	};
	
	var getRemoteValue = function(jq, value) {
		var opt = $(jq).data("option");
		var keyMap = opt["keyMap"];
		var idKey = keyMap["idKey"];
		var textKey = keyMap["textKey"];
		var queryParam = $.extend(true,{},opt["queryParams"]);
		queryParam[opt["filterParam"]] = value;
		var idArr = [];
		var nameArr = [];
		var ajaxOpt = {
				url : opt["filterUrl"],
				data : queryParam,
				async : false,
				success : function(data) {
					var result = $.isArray(data) ? data : data.msg;
					if (result) {
						$.each(result, function(key, obj){
							idArr.push(obj[idKey]);
							nameArr.push(obj[textKey] || obj["name"]);
						});
					}
				}
		};
		fnFormAjaxWithJson(ajaxOpt);
		var ids = idArr.join(",") || value;
		var texts = nameArr.join(",") || value;
		return {"id":ids,"text":texts,"key":ids,"caption":texts};
	};
	
	$.fn.selectTree = function(options, param) {		
		if(typeof options == 'string'){
			var opt=$.fn.selectTree.methods[options];
			if(opt){
				return opt(this, param);
			}
		}
        return this.each(function() {
    	    var state = $(this).data("option");
			if (state) {
				$.extend(state, options);
			} else {
				state = $.extend({}, $.fn.selectTree.defaults,$.fn.selectTree.parseOptions(this), options);
				$(this).data("option", state);
				if(state.theme == "bootstrap") {
					initBootstrap(this);
				} else {
					init(this);
				}
			}     
       });
   };
	
	$.fn.selectTree.defaults = {
		url:"",//数据源url
		queryParams:"",//数据源查询参数
		filterUrl:"",//设值url
		filterParam:"q",//ID对应过滤属性，如：filter_INL_ID
		keyMap:{"idKey":"id","textKey":"text"},//结果取值Map
		valMap:{"idKey":"id","textKey":"name"},//取值字段映射
		multiple:false,
		height:"100%",
		theme:"easyui",//默认框样式，bootstrap
		idValPrefix:"",//id值前缀
		checkOpt:{}, //树check opt
		onChange:null //function(newValue, oldValue) {}
	};
	
	$.fn.selectTree.parseOptions = function(target) {
		var t = $(target);
		return $.extend({}, {
			multiple:t.attr("multiple")
		});
	};
	
	$.fn.selectTree.methods = {
		options:function(jq, param) {
			return jq.data("option");
		},
		getValue: function(jq){
			return $(jq).data("value");
		},
		setValue: function(jq, value){
			if(!$.isPlainObject(value)) {
				if(value) {
					value = getRemoteValue(jq, value);
				} else {
					value = {id:"",text:""};
				}
			}
			jq.val(value.id);
			var opt = jq.data("option");
			if(opt.theme == "bootstrap") {
				jq.prev().find("input:first").val(value.text);
			} else {
				jq.prev().find("input:first").textbox("setValue",value.text);
			}
			$(jq).data("value", value);
		},
		enable : function(jq){
			return jq.each(function() {
				var opt = $(this).data("option");
				if(opt.theme == "bootstrap") {
					$(this).prev().find("input:first").removeProp("readonly");
					$(this).prev().find("a.btn").removeProp("disabled");
				} else {
					$(this).prev().find("input:first").textbox("readonly",false);
				}
			});
		},
		disable : function(jq){
			return jq.each(function() {
				var opt = $(this).data("option");
				if(opt.theme == "bootstrap") {
					$(this).prev().find("input:first").prop("readonly",true);
					$(this).prev().find("a.btn").prop("disabled",true);
				} else {
					$(this).prev().find("input:first").textbox("readonly");
				}
			});
		},
		destroy: function(jq){
			return jq.each(function() {
				var opt = $(this).data("option");
				if(opt.theme == "bootstrap") {
					$(this).prev().remove();
				} else {
					$(this).prev().find("input:first").textbox("destroy");
				}
			});
		}
	};
	
})(jQuery);


/**
 * parser - jQuery EasyUI
 * 
 */
(function($){
	
	/*添加'comboboxsearch'以标签方式加载*/
	$.parser = $.extend({}, $.parser, {
		plugins:['draggable','droppable','resizable','pagination','tooltip',
			         'linkbutton','menu','menubutton','splitbutton','progressbar',
					 'tree','textbox','filebox','combo','combobox','comboboxsearch','combotree','combogrid','numberbox','validatebox','searchbox',
					 'spinner','numberspinner','timespinner','datetimespinner','calendar','datebox','datetimebox','slider',
					 'layout','panel','datagrid','propertygrid','treegrid','datalist','tabs','accordion','window','dialog','form']
	});
})(jQuery);

//textbox支持onkeydown事件
$.fn.datagrid.defaults.editors.textbox.init = function(container,options){
	var _4fb=$("<input type=\"text\" class=\"datagrid-editable-input\">").appendTo(container);
	_4fb.textbox(options);
	if(options && options.readonly) {
		_4fb.textbox("textbox").attr("readonly", "readonly");
	}
	if(options && options["onkeydown"]) { //加入回车事件支持
		_4fb.textbox("textbox").bind("keydown", options["onkeydown"]);
	}
	return _4fb;
};

//text支持onkeydown事件
$.fn.datagrid.defaults.editors.text.init = function(container,options){
	var _4fb=$("<input type=\"text\" class=\"datagrid-editable-input\">").appendTo(container);
	if(options && options.readonly) {
		_4fb.attr("readonly", "readonly");
	}
	if(options && options["onkeydown"]) { //加入回车事件支持
		_4fb.bind("keydown", options["onkeydown"]);
	}
	return _4fb;
};